2014-11-22 58 views
-1

我正在編寫一個小程序,以瞭解如何在Java中運行多個線程。不知道爲什麼我沒有得到任何輸出:Java多線程演示不工作

class NuThread implements Runnable { 
    NuThread() { 
     Thread t = new Thread(this, "NuThread"); 
     t.start(); 
    } 

    public void run() { 
     try { 
       for (int i=0; i<5; i++) { 
       Thread th = Thread.currentThread(); 
       System.out.println(th.getName() + ": " + i); 
       Thread.sleep(300); 
      } 
     } catch (InterruptedException e) { 
      Thread th = Thread.currentThread(); 
      System.out.println(th.getName() + " interrupted."); 
     } 
    } 
} 

public class MultiThreadDemo { 
    public static void main(String[] args) { 
     NuThread t1, t2, t3; 
     try { 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      System.out.println("Main interrupted."); 
     } 
    } 
} 

回答

1

您不是創建NuThread的任何實例。此行:

NuThread t1, t2, t3; 

...只是聲明瞭三個變量。它不創建任何實例。你需要這樣的:

NuThread t1 = new NuThread(); 
NuThread t2 = new NuThread(); 
NuThread t3 = new NuThread(); 

說了這麼多,使得構造函數啓動一個新線程本身有點奇怪......它可能是更好的刪除,只是有:

// TODO: Rename NuThread to something more suitable :) 
NuThread runnable = new NuThread(); 
Thread t1 = new Thread(runnable); 
Thread t2 = new Thread(runnable); 
Thread t3 = new Thread(runnable); 
t1.start(); 
t2.start(); 
t3.start(); 

請注意,對於所有三個線程使用相同的Runnable是可以的,因爲它們實際上不使用任何狀態。

+0

謝謝!這就是Herbert Schildt的書中如何創建線索,雖然我確實認爲你有一點。其他東西(main?)應該是創建和運行線程。 – dotslash 2014-11-22 17:19:47

1

沒有創建的NuThread對象。這就是線程沒有啓動的原因。

在構造函數中啓動線程並不是最好的辦法,請參見here

+0

感謝您的鏈接! – dotslash 2014-11-22 17:21:02