老师,请问为什么我再WrongWayVolatileCantStop.java里面的Producer的run方法里面加上一个休眠。好像是能够正常停止线程,请问为什么?
class Producer implements Runnable{
public volatile boolean canceled = false;
BlockingQueue storage;
public Producer(BlockingQueue storage) {
this.storage = storage;
}
@Override
public void run() {
int num = 0;
try {
while (num <= 100000 && !canceled) {
if (num % 100 == 0) {
storage.put(num);//放到仓库中
System.out.println(num + "是100的倍数,被放到仓库中了。");
}
num++;
//加上这句话,就能停止线程
Thread.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("生产者结束运行");
}
}
}