关于线程的问题

scutxia 2009-06-13 11:41:06

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的,应该一个线程修改了它的值后它的应该会马上更新吧?!
...全文
18 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
swandragon 2009-06-14
  • 打赏
  • 举报
回复
正确使用 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
scutxia 2009-06-14
  • 打赏
  • 举报
回复
3楼的你的结果只是其中的一个看起来比较正常的结果,多运行几遍就有可能出现我那个结果了
heartlesstoanyone 2009-06-14
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 heartlesstoanyone 的回复:]
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
[/Quote]
第二种结果:
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
scutxia 2009-06-14
  • 打赏
  • 举报
回复
哦~加join只是顺便测试join的功能,确保test线程在main线程前完成
xiang7fei 2009-06-14
  • 打赏
  • 举报
回复
是不是有优先级的概念啊
heartlesstoanyone 2009-06-13
  • 打赏
  • 举报
回复
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
WYhack 2009-06-13
  • 打赏
  • 举报
回复
你写Join方法干什么?
WYhack 2009-06-13
  • 打赏
  • 举报
回复
什么玩意,你代码不会写成类啊???乱七八糟的!!!!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧