2010-02-08 75 views
0

在java中實現Runnable接口後,怎麼可能調用線程方法?在java中實現Runnable接口後,怎麼可能調用線程方法?

+5

@spkothale:請編輯你的問題,並提供更多關於你想做什麼的信息。 – 2010-02-08 10:57:24

+3

對我沒有任何意義:) – 2010-02-08 10:59:24

+1

@Suraj:你知道,這是我在這裏的五個月裏見過的第一個罵人詞。 – 2010-02-08 11:00:57

回答

2

我認爲你需要閱讀基本主題。退房this page,具體看標題爲「創建和啓動線程」

0

在任何時候下的示例,從任何地方,你可以調用Thread.currentThread()才能到當前正在運行的線程的引用,沒有什麼幫助。如果您需要覆蓋Thread類中的方法,則需要繼承此方法而不是執行Runnable,但通常不會有這麼做的好理由。

1

您是否將Runnable實現傳遞給Thread構造函數?

這是創建和啓動一個線程是推薦的方式:

class MyRunnable implements Runnable { 
    public void run() { 
     System.out.println("Hello, World!"); 
    } 
} 

public class Main { 
    public static void main(String[] args) { 
     Thread thread = new Thread(new MyRunnable()); 
     thread.start(); 
    } 
} 

這是類似你是如何嘗試呢?

與Java線程一些常見的問題:

  • 調用thread.run()代替thread.start()
  • 通過一個實例調用靜態方法,例如thread.sleep(1000)使當前線程睡眠,而不是目標線程。
1

我假設你有這個問題,因爲當Runnable接口實現時提供的是方法run()的實現。 而我們並沒有明確調用run方法來啓動線程。

public class HelloRunnable implements Runnable { 

    public void run() { 
     System.out.println("Hello from a thread!"); 
    } 

    public static void main(String args[]) { 
     (new Thread(new HelloRunnable())).start(); 
    } 

} 

如果你看的javadoc的方法「開始()`Thread類 的:

在下面的〔實施例(從Java tutorial)線程通過調用start()方法啓動Java API的,這就是它說:

開始 公共無效的start()

導致此線程開始執行; Java虛擬機調用此線程的運行方法。 結果是兩個線程同時運行:當前線程(從調用返回到start方法)和另一個線程(它執行其運行方法)。

0

它是通過使用Thread類構造函數而成爲可能的。其他方式根本不可能。

class ImplementsRunnable implements Runnable { 
public void run() { 
System.out.println("ImplementsRunnable"); 
} 
} 
public class DemoRunnable { 
    public static void main(String args[]) throws Exception { 
      ImplementsRunnable rc = new ImplementsRunnable(); 
      Thread t1 = new Thread(rc); 
      t1.start(); 
    /*here with the help of Constructor of Thread Class we call start method which is not in ImplementsRunnable*/ 
} 
} 
相關問題