下面是密码。输出是1000,b=1000。我不明白为什么每次m2()都会首先运行。
public class TT implements Runnable{
int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(100);
System.out.println("b =" + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2000);
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();// m1() starts
tt.m2();// m2() starts
System.out.println(tt.b);
}
}发布于 2014-11-17 04:05:30
Starting a thread takes a while。一个已经在执行的现有线程有一个很大的优势,它已经存在并且只需要获得一个锁,而另一个线程则依赖于在获得一个锁之前创建一个新线程。一个线程只需要获得一个锁就能赢得比赛,把另一个线程拒之门外,不需要从头开始创建的线程很可能会先到那里。
这仍然是一种竞赛条件,您不应该编写依赖于谁先到达那里的代码。
发布于 2014-11-17 04:06:34
如果您希望tt.m2()在t thread完成后运行,那么它就是工作。在t.join()后面添加t.start()。这使得主线程在t完成其工作后运行。
https://stackoverflow.com/questions/26965272
复制相似问题