线程和创建对象

时间:2012-10-15 21:38:45

标签: java multithreading redundancy

我正在尝试了解线程并在互联网上找到一些例子。这是一个每隔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();
}

这就是我想要完成的事情

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

3 个答案:

答案 0 :(得分:4)

  

我可以将方法run()放在其他地方以便于阅读吗?

是的,您可以像这样创建自己的runnable

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

然后

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

答案 1 :(得分: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();
    }

}

答案 2 :(得分: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");
        }
    }
}