求高人解决线程同步问题 奇怪

muanping85 2012-06-26 11:52:07
public class TT implements Runnable{

int b = 100;

public synchronized void m1() throws Exception {
System.out.println("执行m1");
System.out.println("m1默认优先级是"+Thread.currentThread().getPriority());
b= 1000;
Thread.sleep(7000);
System.out.println("b="+b);
}

public synchronized void m2() throws Exception {
System.out.println("执行m2");
System.out.println("m2默认优先级是"+Thread.currentThread().getPriority());
Thread.sleep(2500);
b= 2000;
//System.out.println("b="+b);
}

@Override
public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws Exception {
System.out.println("main默认优先级是"+Thread.currentThread().getPriority());
TT tt= new TT();
Thread t = new Thread(tt);
t.start();
System.out.println("111111111111");
tt.m2();
System.out.println(tt.b);
}


}

为什么 打印先打印 执行m2 而不是 m1
打印结果测试多次 明明有5秒的时间差了
1000
b = 1000 这个出现概率小

2000
b =2000 这个出现概率大
...全文
67 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
mengmingtao 2012-06-27
  • 打赏
  • 举报
回复
楼主程序里并没有说明要先执行哪一个,因此先执行哪一个都是合理的
nmyangym 2012-06-27
  • 打赏
  • 举报
回复
这个问题不奇怪,因为执行t.start()后,t这个线程进入就绪状态,等待虚拟机调度运行。往往慢于主线程(即当前运行的main()这个线程。)。
楼主可以在t.start()后加一休眠语句,让主线程休眠几毫秒,看看结果。

62,614

社区成员

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

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