当多个线程使用同一个变量时,每个线程都在其本地缓冲中有一个这个变量的拷贝,对这个变量的改变实际上是对这个复制品进行改变。而另一个线程在使用这个变量时还可能一无所知。为了避免这个问题,使用volatile这个关键字对便变量进行修饰,在对变量进行改变时直接作用于主内存。
package javabeat.samples;
class ExampleThread extends Thread {
private volatile int testValue;
public ExampleThread(String str){
super(str);
}
public void run() {
for (int i = 0; i < 3; i++) {
try {
System.out.println(getName() + " : "+i);
if (getName().equals("Thread 1 "))
{
testValue = 10;
}
if (getName().equals("Thread 2 "))
{
System.out.println( "Test Value : " + testValue);
}
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
}
public class VolatileExample {
public static void main(String args[]) {
new ExampleThread("Thread 1 ").start();
new ExampleThread("Thread 2 ").start();
}
}
Java6学习笔记60——多线程编程——使用volatile保障原子性
最新推荐文章于 2025-03-19 21:25:21 发布
本文通过一个简单的多线程示例程序介绍了Java中Volatile关键字的作用和用法。演示了如何利用Volatile确保线程间变量修改的可见性,避免因缓存导致的数据不一致问题。
397

被折叠的 条评论
为什么被折叠?



