2013-03-04 28 views
0

我只是個begginers流,並嘗試學習Java讓我們得到在java中

目標 - 嘗試在Java創建幾流,我的程序一定要創建3個流和1個主流程,比停止。

請告訴我做:

與創建類實現Runnable接口

class NewThread implements Runnable { 
String name; 
Thread t; 

NewThread(String threadname){ 
    name = threadname; 
    t = new Thread (this, name); 
    System.out.println(t); 
    t.start(); 
} 

public void run(){ 
    try { 
     System.out.println("111");// why cant see it? 
     Thread.sleep(1000); 
    } 
    catch (InterruptedException e){ 
     System.out.println(e); 
    } 
    System.out.println("End Thread"); 
} 

而且主:

public class ThreadDemo { 
public static void main (String []args){ 
    new Thread ("F"); 
    new Thread ("S"); 
    new Thread ("T"); 

    try { 
     Thread.sleep(10000); 
    } 
    catch (InterruptedException e){ 

    } 
    System.out.println("End M"); 
} 
} 

我想我會得到像111 3串和一個字符串結束米 -

111 
111 
111 
End M 

,但我得到的只是

End M 

誰能說爲什麼我沒有得到我的PROGRAMM結果3串?

非常感謝大家。

回答

2

您需要創建NewThread情況下,而不是一般的Threads爲您的代碼來執行:

new NewThread("F"); 
... 
+0

OP已經在'NewThread'構造函數中啓動了一個新的'Thread'。所以不需要在'main'中手動啓動'Thread'。 – 2013-03-04 19:33:05

0

使用public static void main如下:

NewThread th1 = new NewThread ("F"); 
NewThread th2 = new NewThread ("S"); 
NewThread th3 =new NewThread ("T"); 
+0

認爲不需要創建var'th1',因爲在'NewThread'中的已實現的類中,我已經創建了新的var't' – gbk 2013-03-04 19:38:44

+0

@Kirill好點。但是它們的創建只是爲了保留以後使用的參考。 ;) – 2013-03-04 19:40:29

+0

好的,謝謝你 - 也許以後我會修改我的代碼 - 但現在只是試圖瞭解java的流程的主要原理 – gbk 2013-03-04 19:43:32

0

找到我的錯誤

我必須寫的

new Thread ("F"); 

public static void main (String []args){ 
    new NewThread ("F"); 
    new NewThread ("S"); 
    new NewThread ("T"); 

,而不是現在其確定。

相關問題