【发布时间】:2010-04-20 10:10:12
【问题描述】:
为什么我们调用start()方法,而后者又调用run()方法?
不能直接拨打run()吗?
请举例说明有区别的地方。
【问题讨论】:
标签: java multithreading concurrency
为什么我们调用start()方法,而后者又调用run()方法?
不能直接拨打run()吗?
请举例说明有区别的地方。
【问题讨论】:
标签: java multithreading concurrency
不,你不能。调用run会在同一个线程中执行run()方法,不会启动新线程。
【讨论】:
start 创建了一个新线程并在该线程内调用run,而run 本身在调用它的线程中执行。
为什么我们调用
start()方法,而后者又调用run()方法?
不,那是不精确的。 start() 反过来不调用 run 方法。
相反,它启动执行 run 方法的线程。这是原生的。
我们不能直接打电话给
run()吗?
如果你直接调用run()你不会启动线程,你只是在同一个调用者方法上执行方法。
请举例说明有区别的地方。
网络上有数百万。因此我不重复。
【讨论】:
其实thread.start()新建了一个线程,有自己的执行场景。
但是thread.run() 没有创建任何新线程,而是在当前正在运行的线程中执行 run 方法。
所以如果你使用thread.run(),那么如果你只想一个线程执行所有运行方法,那么认为多线程有什么用。
【讨论】:
因为 start() 不只是调用 run()。它启动一个新线程并在该线程中调用run()。
【讨论】:
你不能直接运行 run() 方法。每当使用 thread.start() 启动线程时,就会调用 run() 方法并执行进一步的操作。
【讨论】:
主要区别是当程序调用start()方法时,会创建一个新线程,run()方法中的代码会在新线程中执行。如果你调用run() 方法直接不创建新线程,run() 中的代码将在当前线程上执行。
大多数时候调用 run() 是错误或编程错误,因为调用者有意调用 start() 来创建新线程,并且该错误可以被许多静态代码覆盖工具(如 findbugs)检测到。如果你想执行耗时的任务而不是总是调用 start() 方法,否则如果你直接调用 run() 方法,你的主线程将在执行耗时的任务时卡住。在 Java 线程中 start 与 run 之间的另一个区别是您不能在线程对象上调用 start() 方法两次。一旦启动,第二次调用 start() 将在 Java 中抛出 IllegalStateException,而您可以调用 run() 方法两次。
【讨论】:
如果直接调用 run(),代码会在调用线程中执行。通过调用start(),在主线程之外创建一个新线程并并行执行。
【讨论】:
因为start(); 是同步的,而run(); 是简单/常规的方法。就像 java 知道从 main(); 方法开始执行一样。由于线程知道从run();开始执行
这是来自Thread类的源代码:
run();代码:
@Override
public void run() { // overriding from Runnable
if (target != null) {
target.run();
}
}
start();代码:
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
简而言之start();是线程的管理者,如何管理等等,run();是线程工作的起点。
【讨论】:
Thread.start 同步的事实与问题无关。
这是start方法所做的工作
synchronized public void start()
{
//it calls start0() method internally and start0() method does below
//create a real child thread and register with thread scheduler
//create runtime stack for child thread
//call run() on underlying Runtime object
}
【讨论】: