请解释Thread run()和start()方法的输出 [英] Please explain the output from Thread run() and start() methods
问题描述
请解释以下代码的输出:
Please explain the output of the below code:
如果我打电话给 th1.run()
,输出为:
If I call th1.run()
, the output is:
EXTENDS RUN>>
RUNNABLE RUN>>
如果我打电话给 th1.start()
,输出为:
If I call th1.start()
, the output is:
RUNNABLE RUN>>
EXTENDS RUN>>
为何这种不一致?请解释。
Why this inconsistency? Please explain.
class ThreadExample extends Thread{
public void run() {
System.out.println("EXTENDS RUN>>");
}
}
class ThreadExampleRunnable implements Runnable {
public void run() {
System.out.println("RUNNABLE RUN>>");
}
}
class ThreadExampleMain{
public static void main(String[] args) {
ThreadExample th1 = new ThreadExample();
//th1.start();
th1.run();
ThreadExampleRunnable th2 = new ThreadExampleRunnable();
th2.run();
}
}
推荐答案
Thread.start()
方法启动一个新线程,该线程的入口点是 run()
方法。如果直接调用run(),它将在同一个线程中执行。鉴于调用 Thread.start()
将启动一个新的执行线程,可以调用 run()
方法之后(如在你的例子中)执行主方法的其余部分。
The Thread.start()
method starts a new thread, the entry point for this thread is the run()
method. If you call run() directly it will execute in the same thread. Given that calling Thread.start()
will start a new thread of execution, the run()
method may be called after (as in you example) the rest of the main method executes.
更改主要方法以调用 th1.start()
并反复运行,你会看到它有时输出:
Change your main method to call th1.start()
and run repeatedly, you will see that sometimes it outputs:
EXTENDS RUN>>
RUNNABLE RUN >>
有时输出:
RUNNABLE RUN >>
EXTENDS RUN>>
取决于java选择如何安排2个线程。
depending on how java chooses to schedule your 2 threads.
查看 java教程这个。
这篇关于请解释Thread run()和start()方法的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!