我實現了一流的下方,得到如下的輸出:的java多線程(在一個類中的兩個同步的方法)
dsfs2000
2000
b = 1000;
我很奇怪,爲什麼它不是:
b = 1000;
dsfs2000
2000
由於t.start()
會首先撥打m1()
,m2()
應該等到m1()
完成,爲什麼m2()
居然先鎖定?
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;
System.out.println("dsfs" + b);
}
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);
}
}
你在調用t.start(),它會調用線程的run()方法。在run()方法中,您正在調用m1()。由於線程並行執行,因此您直接調用對象的m2(),因此它先執行,然後執行m1()。您可以預測線程的啓動行爲。如果想驗證延遲,則在調用之間放置sysout.currentTimemilliseconds()。 – Shriram
嘗試在't.start()'和'tt.m2()之間添加'Thread.sleep(1000)'' –