案例代码:
public class VolatileDemo {
public static void main(String[] args) throws InterruptedException {
MyRun myRun = new MyRun();
new Thread(myRun, "A").start();
// 主线程休眠1秒
Thread.sleep(1000);
System.out.println("主线程休眠1秒中...");
myRun.isRunning = false;
System.out.println("主线程修改isRunning的值,为:" + myRun.isRunning);
System.out.println("主线程执行完毕!!!");
}
static class MyRun implements Runnable {
public boolean isRunning = true;
@Override
public void run() {
System.out.println("子线程:" + Thread.currentThread().getName() + "执行开始...");
while (isRunning) {
// 死循环
}
System.out.println("子线程:" + Thread.currentThread().getName() + "执行结束!!!");
}
}
}
执行效果图:
说明:主线程执行完毕,子线程死循环结束不了。
实现:主线程执行完毕,修改子线程的变量,解决死循环问题:
变量上添加关键字:volatile
public volatile boolean isRunning = true;
执行代码,看效果:
子线程执行完毕,解决死循环问题。