在 用volatile设置boolean的canceled看似能够停止线程
代码中:
package threadcoreknowledge.stopthreads.volatiledemo;
/**
* 描述: 演示用volatile的局限:part1 看似可行
*/
public class WrongWayVolatile implements Runnable {
private volatile boolean canceled = false;
@Override
public void run() {
int num = 0;
try {
while (num <= 100000 && !canceled) {
if (num % 100 == 0) {
System.out.println(num + "是100的倍数。");
}
num++;
Thread.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
WrongWayVolatile r = new WrongWayVolatile();
Thread thread = new Thread(r);
thread.start();
Thread.sleep(5000);
r.canceled = true;
}
}
r.canceled = true; 执行结束之后,就会停止打印100的倍数,idea 控制台输出:
…
4200是100的倍数。
4300是100的倍数。
Process finished with exit code 0
但是过了很久很久,主线程才结束,远远超过了主线程设置的5秒。
这时候主线程还有打印线程不是应该都结束了吗?请问老师这是怎么回事呢?