多线程可见性问题无法停止

问题遇到的现象和发生背景

我在学习了解 多线程可见性的时候发现程序无法停止想问一下为什么

问题相关代码,请勿粘贴截图

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");
    }
}


运行结果及报错内容

img

我的解答思路和尝试过的方法

我尝试了加锁,但是无效

我想要达到的结果

想让程序停止下来

关键在这
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了,为什么没有退出循环呢?
这个地方没有理解

img


2个东西

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632