0
public class ThreadTest extends Thread {
public static void main(String[] args) {
new ThreadTest().start();
for (int i = 0; i < 10; i++) {
System.out.format("%s %d\n", Thread.currentThread(), i);
}
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.format("%s %d\n", Thread.currentThread(), i);
}
}
}
Thread[Thread-0,5,main] 0
Thread[main,5,main] 0
Thread[main,5,main] 1
Thread[main,5,main] 2
Thread[main,5,main] 3
Thread[main,5,main] 4
Thread[main,5,main] 5
Thread[main,5,main] 6
Thread[main,5,main] 7
Thread[main,5,main] 8
Thread[main,5,main] 9
Thread[Thread-0,5,main] 1
Thread[Thread-0,5,main] 2
Thread[Thread-0,5,main] 3
Thread[Thread-0,5,main] 4
Thread[Thread-0,5,main] 5
Thread[Thread-0,5,main] 6
Thread[Thread-0,5,main] 7
Thread[Thread-0,5,main] 8
Thread[Thread-0,5,main] 9
我感到困惑的是線程運行的順序。當新的ThreadTest.start時,它將首先運行run()方法。但爲什麼它輸出0並繼續運行主線程,你能爲我解釋輸出嗎?
預先感謝您。
由線程調度程序決定的線程順序。不是程序員。 –
兩者都會並行嘗試在兩個循環中添加'Thread.sleep(1000);'並查看結果。 – Kaushal28