2012-10-15 85 views
1

我想了解線程並在互聯網上找到一些例子。這是一個java類,每3秒輸出一次「hello,world」。但我有一種感覺,關於創建Runable對象的部分是多餘的。線程和創建對象

而是寫作的

Runnable r = new Runnable(){ public void run(){...some actions...}}; 

我可以把方法run()別的地方,便於閱讀?

這是我有:

public class TickTock extends Thread { 
    public static void main (String[] arg){ 
     Runnable r = new Runnable(){ 
      public void run(){ 
       try{ 
        while (true) { 
         Thread.sleep(3000); 
         System.out.println("Hello, world!"); 
        } 
       } catch (InterruptedException iex) { 
        System.err.println("Message printer interrupted"); 
       } 
      } 
     }; 
     Thread thr = new Thread(r); 
     thr.start(); 
} 

這就是我想要的東西來完成

public static void main (String[] arg){ 
      Runnable r = new Runnable() //so no run() method here, 
            //but where should I put run() 
      Thread thr = new Thread(r); 
      thr.start(); 
    } 
+1

除了下面實際的答案,考慮學習如何使用IDE的重構工具做這樣的事情(車削匿名類成內部類或「正常」非嵌套類)。 – hyde

回答

4

我可以把run()方法放在別的地方嗎?輕鬆閱讀?

是的,你可以創建自己的可運行這樣

public class CustomRunnable implements Runnable{ 
// put run here 
} 

然後

Runnable r = new CustomRunnable() ; 
Thread thr = new Thread(r); 
3

Java threads tutorial,你可以使用一個稍微不同的風格:

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(); 
    } 

} 
0

只是讓你匿名Runnable類的內部靜態類,就像這樣:

public class TickTock { 

    public static void main (String[] arg){ 
     Thread thr = new Thread(new MyRunnable()); 
     thr.start(); 
    } 

    private static class MyRunnable implements Runnable { 

     public void run(){ 
      try{ 
       while (true) { 
        Thread.sleep(3000); 
        System.out.println("Hello, world!"); 
       } 
      } catch (InterruptedException iex) { 
       System.err.println("Message printer interrupted"); 
      } 
     } 
    } 
} 

或自TickTock已經在您的示例代碼擴展Thread,你可以重寫其run方法:

public class TickTock extends Thread { 

    public static void main (String[] arg){ 
     Thread thr = new TickTock(); 
     thr.start(); 
    } 

    @Override 
    public void run(){ 
     try{ 
      while (true) { 
       Thread.sleep(3000); 
       System.out.println("Hello, world!"); 
      } 
     } catch (InterruptedException iex) { 
      System.err.println("Message printer interrupted"); 
     } 
    } 
}