I'm trying to start/stop Java threads in the following way.
public class ThreadTester {
public static void main(String[] args) {
MyThread mt;
int max = 3;
for (int i = 0; i < max; i++) {
mt = new MyThread();
mt.start();
mt.finish();
}
}
}
public class MyThread extends Thread {
private volatile boolean active;
public void run() {
this.active = true;
while (isActive()) {
System.out.println("do something");
}
}
public void finish() {
this.active = false;
}
public boolean isActive() {
return active;
}
}
Everything works as expected only if max <= 2. Otherwise some threads continue with their output, although isActive should return false. That was at least my expectation.
The question: what is the proper way to synchronize a variable between the "master" and it's "slave" threads?
解决方案
You should initialize active to true during declaration and NOT in a run method.
public class MyThread extends Thread {
private volatile boolean active = true;
public void run() {
// this.active = true;
while (isActive()) {
// do nothing
}
}
public void finish() {
this.active = false;
}
}
The way you are doing it there is a race condition.
Also, the better approach for safely stopping a thread is to use interruption.