2011-07-29 30 views
4

我相信static main方法中的變量也應該是static爲好。 的問題是,我不能在此方法中使用this可言。如果我沒有記錯的話,我必須啓動線程commnad myThread = new ThreaD(this)如何從Java應用程序中的Main方法運行線程?

的下面的代碼,因爲我在線程起始使用this產生錯誤。 我在這裏做了什麼錯?

package app; 

public class Server implements Runnable{ 

    static Thread myThread; 


    public void run() { 
     // TODO Auto-generated method stub 
    } 

    public static void main(String[] args) { 
     System.out.println("Good morning"); 

     myThread = new Thread(this); 



    } 


} 
+0

多線程是一個錯誤的標籤,:)。 –

回答

12

不能使用this因爲主要是一個靜態方法,this指當前實例再沒有。您可以創建一個Runnable對象,您可以通入螺紋:

myThread = new Thread(new Server()); 
myThread.start(); 

這將導致無論你投入運行的方法,通過MyThread的執行的服務器類。

這裏有兩個不同的概念,線程和了Runnable。 Runnable指定了需要完成的工作,Thread是執行Runnable的機制。雖然Thread有一個可以擴展的運行方法,但您可以忽略它並使用單獨的Runnable。

+0

嘿,謝謝!我只是還有一個問題。看來,線程總是使用方法名稱run()。所以,如果我想創建另一個線程從第一個做完全不同的工作,我必須創建一個新的類,並作出'的run()'方法呢?並使用該類創建線程? – user482594

+0

@ user482594:你沒有,但它是一個好主意,讓線程,可運行獨立的。有專注於特定任務的runnables,然後您可以創建線程並將runnable傳遞給它們。 (但也檢查執行者。) –

0
class SimpleThread extends Thread { 
    public SimpleThread(String name) { 
     super(name); 
    } 
    public void run() { 
     for (int i = 0; i < 10; i++) { 
      System.out.println(i + " thread: " + getName()); 
      try { 
       sleep((int)(Math.random() * 1000)); 
      } catch (InterruptedException e) {} 
     } 
     System.out.println("DONE! thread: " + getName()); 
    } 
} 

class TwoThreadsTest { 
    public static void main (String[] args) { 
     new SimpleThread("test1").start(); 
     new SimpleThread("test2").start(); 
    } 
} 
3

變化new Thread(this)new Thread(new Server())

package app; 

public class Server implements Runnable{ 

    static Thread myThread; 


    public void run() { 
     // TODO Auto-generated method stub 
    } 

    public static void main(String[] args) { 
     System.out.println("Good morning"); 

     myThread = new Thread(new Server()); 



    } 


} 
相關問題