问题遇到的现象和发生背景
我在学习了解 多线程可见性的时候发现程序无法停止想问一下为什么
问题相关代码,请勿粘贴截图
import java.sql.Time;
/**
* Created with IntelliJ IDEA.
* 可见性问题
*/
public class VisibilityDemo {
public static void main(String[] args) throws InterruptedException {
TimeComsumingTask timeComsumingTask = new TimeComsumingTask();
Thread thread = new Thread(new TimeComsumingTask());
thread.start();
//指定时间内任务没有执行的话,将其取消
Thread.sleep(1000);
timeComsumingTask.cancel();
}
}
class TimeComsumingTask implements Runnable {
private volatile boolean toCancel = false;
public synchronized void m1(){
if (toCancel) {
System.out.println("Task was canceled");
System.exit(0);
} else {
System.out.println("Task done");
}
}
public void run() {
while (!toCancel) {
if(doExecute()){
break;
}
}
m1();
}
private boolean doExecute() {
boolean isDone = false;
System.out.println("executing...");
//模拟实际操作的时间消耗
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//省略其他代码
return isDone;
}
public void cancel(){
toCancel = true;
System.out.println(this + "canceled");
}
}
运行结果及报错内容
我的解答思路和尝试过的方法
我尝试了加锁,但是无效
我想要达到的结果
想让程序停止下来