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线程能感知到,这时为什么呢
慕无忌7406412
相关分类