我是java新手,我正在嘗試瞭解線程。我期待hello this is thread one
和hello this is thread two
的輸出。但我得到的輸出如下:如何在java中同時運行兩個線程
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
以下是我的代碼。任何人都可以請幫助我爲什麼我得到這個輸出,而不是預期的。我能做什麼來並行運行兩個線程。
public class ThreadDemo {
public static void main(String args[]) {
// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
}
}
};
// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
}
}
};
// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();
// This is the fourth block of code
threadTwo.start();
}
}
只是循環,直到你的線程100,你會看到一些備用輸出 –
看這個http://stackoverflow.com/questions/13263079/run - 兩個線程在最相同的時間,在Java的。 – iCroque
@GerardRozsavolgyi它可能會做,但不一定。因爲它正在做一件非常簡單的事情,所以第一個線程的執行可能總是在第二個線程被調度之前完成。 –