爲什麼每次運行此程序時輸出的順序都不相同?是否由於多個線程試圖同時訪問共享資源?因此,線程執行的方式會是隨機的嗎?爲什麼每次運行此程序時輸出的順序都不相同?
我從螺紋4 你好從線程從線程3 輸出
的java MyThreadExample 你好從線程1 你好從線3 你好2
的java MyThreadExample 你好從線程1 你好你好from thread 2 Hello from thread 4
java MyThreadExample
Hello from thread 1
Hello from thread 4
Hello from thread 3
Hello from thread 2
代碼:
import java.io.*;
import java.lang.*;
class MyThreadExample {
public static void main(String[] args) {
HelloThread ht1 = new HelloThread(1);
HelloThread ht2 = new HelloThread(2);
HelloThread ht3 = new HelloThread(3);
HelloThread ht4 = new HelloThread(4);
ht1.start();
ht2.start();
ht3.start();
ht4.start();
}
}
class HelloThread extends Thread {
int threadID;
HelloThread(int threadID) {
this.threadID = threadID;
}
public void run() {
System.out.println("Hello from thread " + this.threadID);
}
} // end Thread
它與OS有關。一旦線程啓動,O將調度線程。一些人得到高度重視,一些人得到低優先級 – 2014-10-11 18:27:23
在編寫任何此類代碼之前,您應該閱讀併發/多線程的基礎知識。如果你這樣做,那麼你就不會有這個問題。 – 2014-10-11 18:29:00