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

这就是我想要完成的

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

3 回答 3

4

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

是的,您可以像这样创建自己的可运行文件

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

进而

Runnable r = new CustomRunnable () ;
Thread thr = new Thread(r);
于 2012-10-15T21:41:15.703 回答
3

Java 线程教程中,您可以使用稍微不同的样式:

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

}
于 2012-10-15T21:41:03.667 回答
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");
        }
    }
}
于 2012-10-15T21:45:00.970 回答