volatile关键字实现线程间通信(生产者-消费者)
作者:
Roc_8
,
2025-04-14 23:00:06
· 广东
,
所有人可见
,
阅读 1
public class SharedVariableExample {
private static volatile boolean flag = false;
public static void main(String[] args) {
Thread producer = new Thread(() -> {
try{
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
flag = true;
System.out.println("Producer: Flag is set to true.");
});
Thread consumer = new Thread(() -> {
while (!flag){
}
System.out.println("Consumer: Flag is now true.");
});
producer.start();
consumer.start();
}
}