您的位置:程序门 -> java -> j2se / 基础类



关于一个synchronized同步程序的疑惑??


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


关于一个synchronized同步程序的疑惑??[已结贴,结贴人:robbiezr]
发表于:2007-02-01 00:04:14 楼主
public   class   tt   implements   runnable   {
int   b   =   100;

public   synchronized   void   m1()   throws   exception{
//thread.sleep(2000);
b   =   1000;
thread.sleep(5000);
system.out.println( "b   =   "   +   b);
}

public   synchronized   void   m2()   throws   exception   {
thread.sleep(2500);
b   =   2000;
}

public   void   run()   {
try   {
m1();
}   catch(exception   e)   {
e.printstacktrace();
}
}

public   static   void   main(string[]   args)   throws   exception   {
tt   tt   =   new   tt();
thread   t   =   new   thread(tt);
t.start();

tt.m2();
system.out.println(tt.b);
}
}

程序如上,

输出为:
1000
b=1000

谁能可以说一下程序执行的流程.
另外synchronized所指定的方法应该是一个原子操作吗?
发表于:2007-02-01 00:44:151楼 得分:10
因为m1(),m2()是synchronized的,所以t.start()执行了run()中的m1()后,在m1()没有结束之前,变量b是不会被m2()访问的,所以就继续执行system.out.println(tt.b),即得出上面的结果。


快速检索

热门点击