我正試圖提高我的JAVA。現在我有一個問題,我不明白線程。Java:線程問題
我試圖代碼是,
public class MyThread implements Runnable {
private int end;
private String name;
public MyThread(String name, int end) {
this.end = end;
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < end; i++) {
System.out.println(name + " : " + i);
}
}
}
public class ThreadLesson {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread("thread1", 6));
Thread thread2 = new Thread(new MyThread("thread2", 5), "thread2");
thread1.start();
thread2.start();
}
}
在教訓輸出
thread1 : 0
thread2 : 0
thread2 : 1
thread2 : 2
thread1 : 1
thread2 : 3
thread1 : 2
thread2 : 4
thread1 : 3
thread1 : 4
thread1 : 5
我outout是
Thread1:0
Thread2:0
Thread1:1
Thread1:2
Thread1:3
Thread1:4
Thread1:5
Thread2:1
Thread2:2
Thread2:3
Thread2:4
我的問題是, 爲什麼我出不同樣的課程輸出?有一些問題,或者誰寫了這一課,只是編輯輸出爲文章beaty。
你不能事先知道將按哪個順序執行線程。如果再次運行它,你很可能會得到不同的結果。 – Averroes