Re: thread testing done flag
Or, the following works.., but can it cause a problem?
import java.util.concurrent.atomic.AtomicBoolean;
public class Test {
private AtomicBoolean done = new AtomicBoolean(false);
class TestThread extends Thread {
private String name;
private AtomicBoolean done;
public TestThread(final String n, final AtomicBoolean d) {
name = n;
done = d;
}
public void run() {
while (true) {
System.out.println(name);
try {
Thread.currentThread().sleep(100);
} catch (Exception ex) {
System.out.println("" + ex);
return;
}
if (done.get()) {
return;
}
}
}
}
public static void main(String[] args) throws Exception {
Test t = new Test();
t.run();
}
public void run() {
TestThread ta = new TestThread("a", done);
TestThread tb = new TestThread("b", done);
ta.start();
tb.start();
for (int i = 0; i < 10; ++i) {
System.out.println("main: " + i);
try {
Thread.currentThread().sleep(100);
} catch (Exception ex) {
System.out.println("" + ex);
break;
}
}
done.set(true);
try {
ta.join();
tb.join();
} catch (Exception ex) {
System.out.println("" + ex);
}
}
}