【Java6学习笔记】多线程编程中使用volatile保障原子性

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

当多个线程使用同一个变量时,每个线程都在其本地缓冲中有一个这个变量的拷贝,对这个变量的改变实际上是对这个复制品进行改变。而另一个线程在使用这个变量时还可能一无所知。为了避免这个问题,使用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();
    }
}

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

posted @ 2012-12-17 20:50  gnuhpc  阅读(454)  评论(0编辑  收藏  举报