直接上代码:
public class Test implements Runnable{
// 未经volatile 修饰的变量
private boolean asleep;
// volatile 修饰的变量
// private volatile boolean asleep;
public void run() {
while (!asleep){
countSheep();
}
}
private void countSheep(){
// 添加yield或者sleep方法,不加volatile,也能正常运行,猜想应该是在线程恢复运行后会重新刷新线程缓存,系统控制的线程切换不会刷新,待验证
// Thread.yield();
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
public void setAsleep(){
this.asleep = true;
}
public static void main(String[] args){
int i = 0;
while (i<1000){
Test test = new Test();
Thread thread1 = new Thread(test);
thread1.start();
Thread thread2 = new Thread(new Sleep(test,thread1));
thread2.start();
while (thread1.isAlive()||thread2.isAlive());
System.out.println(i);
i++;
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("start success");
}
}
class Sleep implements Runnable{
private Test test;
private Thread countSheepThread;
public Sleep(Test test,Thread thread){
this.test = test;
this.countSheepThread = thread;
}
public void run() {
test.setAsleep();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(countSheepThread.isAlive()){
System.out.println("出错");
}
}
}
参数里不加-server也出错,jdk版本是1.8.0_144,这里和《java并发编程开发实战》里说的不同,遗留问题。