开发者

Why is run method not called?

package threadwor开发者_如何学Gok;

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

When I run this code, it Prints Creating Thread and Starting Thread. But doesn't prints Thread Running, that means run function is not at all called. Why is it so?


You have to call start() on the thread to get it to start; e.g.

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

If you were extending Thread, you would create a new thread and call start() on it like this:

new MyThread().start();

Since you are not extending Thread, but your class implements Runnable:

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


If I were in your shoes, I would start the thread inside main, like this:

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

Leaving the constructor for WorkingWithThreads empty:

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

In general, it is not a good idea to create the Thread inside the constructor for WorkingWithThreads, because the runnable (i.e., an instance of WorkingWithThreads) must be fully constructed before you pass it to an instance of Thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜