package com.example.demo.synchronized_test;
import lombok.Data;
public class Test2 {
public static void main(String[] args) throws InterruptedException {
S s = new S();
if(s.isFlag()){
System.out.println("flag is true");
}
T1 t1 = new T1(s);
t1.start();
Thread.sleep(500);
T2 t2 = new T2(s);
t2.start();
Thread.sleep(500);
if(s.isFlag()){
System.out.println("flag is true");
}else{
System.out.println("flag is false");
}
}
}
@Data
class S{
private boolean flag = true;
}
class T1 extends Thread{
private S s;
public T1(S s) {
this.s = s;
}
@Override
public void run() {
System.out.println("begin t1 ...");
while(s.isFlag()){
}
System.out.println("end t1 ...");
}
}
class T2 extends Thread{
private S s;
public T2(S s) {
this.s = s;
}
@Override
public void run() {
s.setFlag(false);
}
}
程序运行结果,如下图所示:有个疑问,t1线程和main线程应该都感知不到t2线程对变量flag的修改,但是结果证明t1线程感知不到,但是main线程能感知到,这时为什么呢
3 回答
已采纳
慕无忌7406412
TA贡献4条经验 获得超1个赞
你为什么会觉得t1线程和t2线程都感知不到s里面的flag变量呢?其实它们两个都能感知得到,你只需要把你t1里面的run方法改一下,就可以知道.见下图:
添加回答
举报
0/150
提交
取消