2014-10-22 65 views
-2

我該如何確保我的代碼使用了多線程機制?第一個代碼看起來像不使用多線程機制。爲什麼第二代碼的結果是無序?如何確認我的java使用多線程機制運行

public class ThreadDemo9_2 
{ 
    public static void main(String[] args) 
    { 
     TestThread t = new TestThread() ; 
     new Thread(t).start(); 
     for(int i =0;i < 5;i++) 
     { 
      System.out.println("main thread is running"); 
     } 
    } 
} 
class TestThread implements Runnable 
{ 
    public void run() 
    { 
     for(int i =0;i<5;i++) 
     { 
      System.out.println("test thread is running"); 
     } 
    } 
} 

提前碼結果如下

main thread is running 
main thread is running 
main thread is running 
main thread is running 
main thread is running 
test thread is running 
test thread is running 
test thread is running 
test thread is running 
test thread is running 

好,我改變了代碼,如圖below.Just加上「我」來區分。

public class ThreadDemo9_2 
{ 
    public static void main(String[] args) 
    { 
     TestThread t = new TestThread() ; 
     new Thread(t).start(); 
     for(int i =0;i < 5;i++) 
     { 
      System.out.println(i+"main thread is running"); 
     } 
    } 
} 
class TestThread implements Runnable 
{ 
    public void run() 
    { 
     for(int i =0;i<5;i++) 
     { 
      System.out.println(i+"test thread is running"); 
     } 
    } 
} 

結果是:

0main thread is running 
0test thread is running 
1main thread is running 
1test thread is running 
2main thread is running 
2test thread is running 
3main thread is running 
4main thread is running 
3test thread is running 
4test thread is running 
+3

Java具有多線程,並且該功能有效。 – Raedwald 2014-10-22 08:18:03

+0

是的,我正在學習java的多線程。我只想知道爲什麼我的第一個代碼的結果看起來像沒有多線程一樣? – wuyuanyi 2014-10-22 08:22:16

+0

檢查[Java 101:瞭解Java線程,](http://www.javaworld.com/article/2074217/java-concurrency/java-101-understanding-java-threads--part-1--introducing-threads -and-runnables.html)。請注意,您的計算機每秒可執行大約1毫升的操作。嘗試添加** Thread.sleep(10); **到方法並增加發生率> 20 – 2014-10-22 08:25:23

回答

1

沒有你的線程阻塞的任何進一步的同步/等待對方你不能在什麼時候你的一個線程獲取的時間來運行多長時間預測。

如果你在第一個例子中循環了幾百次,你會看到輸出也是「無序的」。

+0

我在第一個示例中循環了300次,它仍然是有序的 – wuyuanyi 2014-10-22 08:43:57

+0

我添加了thread.sleep(10);,然後reuslt是無序的。 – wuyuanyi 2014-10-22 08:52:02

相關問題