我在学习了解 多线程可见性的时候发现程序无法停止想问一下为什么
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");
}
}
我尝试了加锁,但是无效
想让程序停止下来
关键在这
TimeComsumingTask timeComsumingTask = new TimeComsumingTask();
Thread thread = new Thread(new TimeComsumingTask());
你声明了2个对象,把类实例化了2次
一个在主线程里,一个作为子线程执行
而你后面cancel的是主线程里的那一个,跟子线程里的无关
改为
Thread thread = new Thread(timeComsumingTask );
doExecute()方法返回的一直都是false,所以一直都没有break出去,而上一行的while循环条件判断的一直都是true,所以就一直在循环打印 executing...
可是后面加了
timeComsumingTask.cancel();
已经将 toCancel 变量置为 true了,为什么没有退出循环呢?
这个地方没有理解