Java中有趣的线程行为

avi*_*ara 5 java multithreading

我在Java中学习了多线程的概念,在那里我遇到了这个非常有趣的行为.我正在尝试各种创建线程的方法.现在问的是我们在扩展a Thread而不是实现Runnable接口的时候.

在旁注中,我知道它实现Runnable接口而不是扩展Thread类是完美的OO意义,但是出于这个问题的目的,让我们说我们扩展了Thread类.

t我的扩展Thread类的实例,我有一个代码块在后台执行,写在我run()Thread类的方法中.

它完全在后台运行t.start(),但我有点好奇并称之为t.run()方法.在主线程中执行的代码片段!

t.start()t.run()不是做什么的?

nab*_*lex 8

这就是班级的作用.t.start()实际上将启动一个新线程,然后在该线程中调用run().如果直接调用run(),则在当前线程中运行它.

public class Test implements Runnable() {
    public void run() { System.out.println("test"); }
}

...

public static void main(String...args) {
    // this runs in the current thread
    new Test().run();
    // this also runs in the current thread and is functionally the same as the above
    new Thread(new Test()).run();
    // this starts a new thread, then calls run() on your Test instance in that new thread
    new Thread(new Test()).start();
}
Run Code Online (Sandbox Code Playgroud)

这是预期的行为.