public class VolatileTest { public static void main(String[] args) { VolatileExample example = new VolatileExample(); // 启动一个线程,修改flag的值 new Thread(() -> { example.setFlag(); System.out.println(Thread.c
时间: 2024-02-14 16:24:46 浏览: 71
volatile源码分析1
public class VolatileTest {
public static void main(String[] args) {
VolatileExample example = new VolatileExample();
// Start a thread to modify the value of flag
new Thread(() -> {
example.setFlag();
System.out.println(Thread.currentThread().getName() + ": Flag is set to " + example.getFlag());
}).start();
}
}
class VolatileExample {
private volatile boolean flag;
public void setFlag() {
flag = true;
}
public boolean getFlag() {
return flag;
}
}
```
This code demonstrates the use of the `volatile` keyword in Java to ensure visibility of changes made by one thread to other threads. The `VolatileExample` class has a `flag` variable that is marked as `volatile`. When the `setFlag()` method is called, it sets the value of `flag` to `true`. In the `main()` method, a new thread is started to call `setFlag()`. The `getFlag()` method is used to retrieve the value of `flag`.
Please note that I am not executing the code, but providing an explanation.
阅读全文