[英]Why doesn't the volatile keyword work as expected in java code?
我在Java学习并发知识。 关于 volatile 关键字,它应该使变量在不同的线程中可见。 但在我的演示代码中,它似乎没有按预期工作。 class 中实现Runnable
的方法run()
永远不会停止。
public class VisibilityDemo {
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(new TimeConsumingTask());
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}
class TimeConsumingTask implements Runnable {
private volatile boolean toCancel = false;
@Override
public void run() {
while (! toCancel) {
System.out.println("executing...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (toCancel) {
System.out.println("Task was canceled.");
} else {
System.out.println("Task done.");
}
}
public void cancel() {
toCancel = true;
System.out.println(this + " canceled.");
}
}
在您的主要方法中,您有两个任务实例:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask(); //<-- one
Thread thread = new Thread(new TimeConsumingTask()); //<-- two
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel(); //<-- cancel() on first
}
}
您将一个传递给Thread
构造函数,然后在另一个上调用cancel
。 您需要在传递给Thread
的实例上调用cancel
,如下所示:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(timeConsumingTask); //<-- difference here
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.