package com.leetcode.multithreading.licm;
/**
* @description:
*
* 通过volatile实现多线程间共享变量的可见性
*
* @author: licm
* @create: 2021-07-26 10:55
**/
public class VolatileTest {
private volatile boolean flag = true;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
private static class ChangeFlag extends Thread {
private VolatileTest volatileTest;
public ChangeFlag(VolatileTest volatileTest) {
this.volatileTest = volatileTest;
}
@Override
public void run() {
while (volatileTest.flag) {
System.out.println("flag是 true");
}
System.out.println("flag 已经变成了false");
}
}
public static void main(String[] args) throws InterruptedException {
VolatileTest volatileTest = new VolatileTest();
ChangeFlag addCount = new ChangeFlag(volatileTest);
addCount.start();
Thread.sleep(50);
volatileTest.setFlag(false);
ChangeFlag addCount1 = new ChangeFlag(volatileTest);
addCount1.start();
}
}
不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/u_12550160/3206502,作者:小傻孩丶,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。