C
cppaddict
I'm looking for an elegant way to start and stop threads without
killing them, in order to avoid the overhead of unnecessary thread
creation. My awkward attempt to do this is below. I'd appreciate any
comments or suggestions about how to write code that accomplishes the
same thing more cleanly.
Thanks,
cpp
Code follows:
public class Test implements Runnable{
Thread mThread;
boolean mStopped;
public Test() {
mThread = new Thread(this);
mThread.start();
}
public synchronized void start() {
mStopped = false;
notifyAll();
}
public synchronized void stop() {
mStopped = true;
}
public synchronized void run() {
while (true) {
//give other threads a chance to start and
stop this one
try { wait(10); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
//if it does get stopped, pause here till its
restarted
if (mStopped) {
System.out.println("Stopping...");
try { wait(); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
}
System.out.println("Testing...");
}
}
public static void main (String[] args) {
Test t = new Test();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.stop();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.start();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.stop();
}
}
killing them, in order to avoid the overhead of unnecessary thread
creation. My awkward attempt to do this is below. I'd appreciate any
comments or suggestions about how to write code that accomplishes the
same thing more cleanly.
Thanks,
cpp
Code follows:
public class Test implements Runnable{
Thread mThread;
boolean mStopped;
public Test() {
mThread = new Thread(this);
mThread.start();
}
public synchronized void start() {
mStopped = false;
notifyAll();
}
public synchronized void stop() {
mStopped = true;
}
public synchronized void run() {
while (true) {
//give other threads a chance to start and
stop this one
try { wait(10); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
//if it does get stopped, pause here till its
restarted
if (mStopped) {
System.out.println("Stopping...");
try { wait(); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
}
System.out.println("Testing...");
}
}
public static void main (String[] args) {
Test t = new Test();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.stop();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.start();
try { Thread.currentThread().sleep(1000); }
catch (InterruptedException e) {
System.out.println("Interrupted Exception!"); }
t.stop();
}
}