为什么不调用run方法?

时间:2011-04-17 05:32:54

标签: java multithreading runnable

package threadwork;

public class WorkingWithThreads implements Runnable {

    public static void main(String[] args) {
        WorkingWithThreads wwt = new WorkingWithThreads();
    }

    public WorkingWithThreads() {
        System.out.println("Creating Thread");
        Thread t = new Thread();
        System.out.println("Starting Thread");
        t.start();
    }

    @Override
    public void run() {
        System.out.println("Thread Running");

        for (int i = 0; i < 5; i++) {
            System.out.println("Thread:" + i);
            try {
                Thread.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

当我运行此代码时,它会打印创建线程和启动线程。但是不打印Thread Running,这意味着运行函数根本没有被调用。为什么会这样?

2 个答案:

答案 0 :(得分:2)

你必须在线程上调用start()才能启动它; e.g。

Thread t = new Thread();
t.start();

如果你正在扩展Thread,你会创建一个新的主题并在其上调用start(),如下所示:

new MyThread().start();

由于您未展开Thread,但您的班级实施了Runnable

new Thread(new WorkingWithThreads()).start();

答案 1 :(得分:0)

如果我在你的鞋子里,我会在main中开始主题,就像这样:

public static void main(String[] args) {
  WorkingWithThreads wwt = new WorkingWithThreads();
  System.out.println("Creating Thread");
  Thread tzero = new Thread(wwt);
  System.out.println("Starting thread");
  tzero.start();
}

WorkingWithThreads的构造函数为空:

public WorkingWithThreads() {
  System.out.println("Creating Runnable");
}

通常,在Thread的构造函数中创建WorkingWithThreads不是一个好主意,因为runnable(即WorkingWithThreads的实例)必须完全构造< em>在之前将其传递给Thread的实例。