线程的可见性代码演示
什么是线程间的可见性?
一个线程对共享变量值的修改,能够及时的被其他线程看到。
1、演示线程的可见性:这里创建两个线程,和同一个对象,主线程以自旋的方式占用CPU资源,并且修改公共数据;异步线程根据公共对象的属性来打印对应的值。
2、正常情况下主线程打印完成后,两个异步线程紧跟就应该打印,看看你运行后是什么样呢,异步程序是否还在循环?
public static void main(String[] args){
TestBN testBN = new TestBN(1,false);
Mthread mthread = new Mthread(testBN);
Mthread2 mthread2 = new Mthread2(testBN);
mthread.setName("isTrue");
mthread2.setName("isTwo");
mthread.start();
mthread2.start();
for (int i = -100; i <= 100; i++) {
if (i == 0) {
testBN.ready = true;
System.out.println(testBN);
}
if(i>0){
System.out.println("i = " + i);
}
}
下面是对象实体类和两个线程类:
class Mthread extends Thread {
TestBN testBN;
public Mthread(TestBN testBN) {
this.testBN = testBN;
}
@Override
public void run() {
while (true) {
if (testBN.ready) {
testBN.num = 2;
System.out.println(Thread.currentThread().getName() + " ->ok");
break;
}
}
}
}
class Mthread2 extends Thread {
TestBN testBN;
public Mthread2(TestBN testBN) {
this.testBN = testBN;
}
@Override
public void run() {
while (true) {
if (testBN.num==2) {
System.out.println(Thread.currentThread().getName() + " ->ok");
break;
}
}
}
}
@AllArgsConstructor
class TestBN{
int num;
boolean ready;
}