线程同步问题,请帮忙

zhuangyao 2008-11-14 05:27:19

下面的类在运行的时候,m1只睡了500,而m2睡了9500,在运行的时候确是m2先输出...

package lang.thread.demo;


public class NewThread implements Runnable{
int b = 100;

public synchronized void m1(){
b = 1000 ;
System.out.println("m1 : " + b);
try{
Thread.sleep(500);
}catch(InterruptedException ex){
ex.printStackTrace();
}
System.out.println("b=" + b);
}


public synchronized void m2(){
try{
Thread.currentThread().sleep(9500);
}catch(InterruptedException ex){
ex.printStackTrace();
}
b = 2000 ;
System.out.println("m2:" + b);
}

public void run(){
m1();
}


public static void main(String[] args){
NewThread nt = new NewThread();
Thread thread = new Thread(nt);
thread.start();
nt.m2();
System.out.println(nt.b);
}

}

结果:

m2:2000
2000
m1 : 1000
b=1000
...全文
119 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhuangyao 2008-11-14
  • 打赏
  • 举报
回复
明白了...谢谢。
老紫竹 2008-11-14
  • 打赏
  • 举报
回复
thread.start();
nt.m2();
你认为这2个语句到底谁的速度快一些
1 线程启动,然后运行到run的方法,拿到同步锁
2 当前main,继续运行也拿到了同步锁。
我永远支持2,呵呵!
natee 2008-11-14
  • 打赏
  • 举报
回复
因为synchronized方法。你执行synchronized方法的时候,它会把它执行完或者自己调用wait函数才能让出cpu吧。
你把synchronized去掉后就可以得到预期结果了
scusong 2008-11-14
  • 打赏
  • 举报
回复
线程不一定在调用start()就会马上执行,由JVM决定

62,614

社区成员

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

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