我正在尝试通过以下方式启动/停止 Java 线程。
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;
}
}
仅当 max <= 2 时,一切都按预期工作。否则,尽管 isActive
应返回 false,但某些线程会继续其输出。这至少是我的预期。
问题:在“主”线程和“从”线程之间同步变量的正确方法是什么?
最佳答案
您应该在声明期间而不是在运行方法中将 active
初始化为 true
。
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;
}
}
你这样做的方式存在竞争条件。
此外,安全停止线程的更好方法是使用中断。
关于Java:线程间变量的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4160211/