這裏是我的代碼:多線程輸出解釋
public class thread1 implements Runnable {
public static void main(String[] args) {
thread1 d = new thread1();
new Thread(d).start();
Thread t1 = new Thread(d);
t1.start();
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
sleep1(i);
sleep2(i);
}
}
public void sleep1(int i) {
try {
Thread.sleep(1000);
System.out.println("sleep 1 and i= " + i);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void sleep2(int i) {
try {
Thread.sleep(1000);
System.out.println("sleep 2 and i= " + i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
這是我的輸出:
sleep 1 and i= 0
sleep 1 and i= 0
sleep 2 and i= 0
sleep 2 and i= 0
sleep 1 and i= 1
sleep 1 and i= 1
sleep 2 and i= 1
sleep 1 and i= 2
sleep 2 and i= 1
sleep 2 and i= 2
sleep 1 and i= 2
sleep 2 and i= 2
爲什麼會出現在每個特定的睡眠和我一個額外的副本。
例如:
sleep 1 and i= 0
sleep 1 and i= 0
爲什麼?
我該如何清楚地確定哪個線程正在一次運行並切換到另一個線程?
編輯
我改變sleep1()
到和輸出是這樣的:(兩種方法都是同步的)
sleep 1 and i= 0
sleep 2 and i= 0
sleep 1 and i= 0
sleep 2 and i= 0
sleep 1 and i= 1
sleep 1 and i= 1
sleep 2 and i= 1
sleep 1 and i= 2
sleep 2 and i= 2
sleep 2 and i= 1
sleep 1 and i= 2
sleep 2 and i= 2
我知道,方法不能同時運行,但是這是如何發生的這裏?
'Thread.getCurrentThread()。getName()'將幫助您可視化線程 –
可能的重複[Java Threading Concept:Output Explanation](http://stackoverflow.com/questions/8064024/java-threading-concept -output-explanation) –