日期:2014-05-20  浏览次数:20644 次

求高人解决线程同步问题 奇怪
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 这个出现概率大


------解决方案--------------------
这个问题不奇怪,因为执行t.start()后,t这个线程进入就绪状态,等待虚拟机调度运行。往往慢于主线程(即当前运行的main()这个线程。)。
楼主可以在t.start()后加一休眠语句,让主线程休眠几毫秒,看看结果。
------解决方案--------------------
楼主程序里并没有说明要先执行哪一个,因此先执行哪一个都是合理的