我自己正在学习Java中的多线程和并发。请帮我理解这段代码。我正在创建一个带有“停止”布尔变量的线程,“run”方法会连续循环,直到主线程在休眠2秒后将停止变量设置为true为止。但是,我观察到这段代码在无限循环中运行。我在这里做错什么了?
public class Driver {
public static void main(String[] args) {
ThreadWithStop threadWithStop = new ThreadWithStop();
Thread thread = new Thread(threadWithStop);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadWithStop.stopThread();
}
}
class ThreadWithStop implements Runnable {
private boolean stop;
public ThreadWithStop() {
this.stop = false;
}
public void stopThread() {
this.stop = true;
}
public boolean shouldRun() {
return !this.stop;
}
@Override
public void run() {
long count = 0L;
while (shouldRun()) {
count++;
}
System.out.println(count+"Done!");
}
}
发布于 2021-10-20 14:28:26
它不一定会停止,但它可能会。在以某种方式与stop
同步之前,通过从主线程调用stopThread()
对ThreadWithStop
所做的更改不能保证对ThreadWithStop
是可见的。
实现这一目标的一种方法是使用synchronized
关键字保护对变量的访问。例如,请参阅官方的同步方法教程。
通过以下更改,可以保证对stop
的更改是可见的。
class ThreadWithStop implements Runnable {
private boolean stop;
public ThreadWithStop() {
this.stop = false;
}
public synchronized void stopThread() {
this.stop = true;
}
public synchronized boolean shouldRun() {
return !this.stop;
}
@Override
public void run() {
long count = 0L;
while (shouldRun()) {
count++;
}
System.out.println(count+"Done!");
}
}
https://stackoverflow.com/questions/69647723
复制相似问题