2012-10-15 2 views
1

스레드에 대해 배우고 인터넷에서 몇 가지 예제를 찾으려고합니다. 이것은 3 초마다 "hello, world"를 출력하는 Java 클래스입니다. 하지만 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(); 
} 

그리고 이것은 내가, 당신이 약간 다른 스타일을 사용할 수있는 Java threads tutorial에서

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

을 수행 할 것입니다 :

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

또는부터이미 예제 코드에 Thread을 확장, 당신은 단지 그 run 메소드를 오버라이드 (override) 할 수 있습니다

아래 실제 답변에 추가
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"); 
     } 
    } 
}