public class ThreadTest extends Thread { static volatile String msg = "hello";
int start;

public ThreadTest(int i,String name){
this.start = i;
this.setName(name);
} public static void main(String[] args) {
ThreadTest test = new ThreadTest(10,"test");
ThreadTest test1 = new ThreadTest(20,"test1");
test.start();
test1.start();
try {
test.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main's msg is "+msg);
System.out.println("main stoped");
} public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName+" running");
for (int i = start; i < start+4; i++) {
msg = msg + " " + i;
}
System.out.println(threadName+"'s msg is "+ msg);
System.out.println(threadName+" stoped");
}
}主要是三个线程test,test1和main对静态变量msg进行修改和打印。
在多次运行后出现了下面的一个结果:
test running
test's msg is hello 10 11 12 13
test stoped
test1 running
test1's msg is hello 10 11 12 13 20 21 22 23
test1 stoped
main's msg is hello 10 11 12 13
main stoped
很奇怪,在test1线程将msg修改为hello 10 11 12 13 20 21 22 23后,main线程打印msg结果却是hello 10 11 12 13?应该是hello 10 11 12 13 20 21 22 23才对啊,msg还是volatile的,应该一个线程修改了它的值后它的应该会马上更新吧?!

解决方案 »

  1.   

    XP SP3,Core 2 CPU,2.5G内存,JDK 1.6.13,的运行结果为:
    test running
    test1 running
    test1's msg is hello 20 21 22 23
    test1 stoped
    test's msg is hello 20 21 22 23 10 11 12 13
    test stoped
    main's msg is hello 20 21 22 23 10 11 12 13
    main stoped
      

  2.   

    哦~加join只是顺便测试join的功能,确保test线程在main线程前完成
      

  3.   

    第二种结果:
    test running
    test's msg is hello 10 11 12 13
    test stoped
    main's msg is hello 10 11 12 13
    main stoped
    test1 running
    test1's msg is hello 10 11 12 13 20 21 22 23
    test1 stoped
      

  4.   

    正确使用 volatile 变量的条件
    您只能在有限的一些情形下使用 volatile 变量替代锁。要使 volatile 变量提供理想的线程安全,必须同时满足下面两个条件:    * 对变量的写操作不依赖于当前值。
        * 该变量没有包含在具有其他变量的不变式中。
    实际上,这些条件表明,可以被写入 volatile 变量的这些有效值独立于任何程序的状态,包括变量的当前状态。 
    参考
    http://www.xland.com.cn/article/7/132/0903/30877.htm
    http://www.ibm.com/developerworks/cn/java/j-jtp06197.html