运行和启动线程的区别 [英] Difference between running and starting a thread
问题描述
我不明白启动和运行线程之间的区别,我测试了这两种方法并且它们输出相同的结果,首先我使用了 run() 的组合并在同一线程上启动并且它们执行相同的功能如下:
i don't understand the difference between starting and running a thread, i tested the both methods and they outputs the same result, first i used a combination of run() and start on the same thread and they did the same function as follows:
public class TestRunAndStart implements Runnable {
public void run() {
System.out.println("running");
}
public static void main(String[] args) {
Thread t = new Thread(new TestRunAndStart());
t.run();
t.run();
t.start();
}
}
输出为:
running
running
running
然后我看到 run() 方法的 javadoc 说:如果这个线程是使用一个单独的 Runnable run 对象构造的,那么该 Runnable 对象的 run 方法被调用;否则,此方法不执行任何操作并返回
,因此我尝试使用 run() 方法而不使用单独的可运行对象,如下所示:
then i saw the javadoc of the run() method said that:
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns
so i tried to use the run() method without a separate runnable as follows :
public class TestRun extends Thread {
public void run(){
System.out.println("Running Normal Thread");
}
public static void main(String[]args){
TestRun TR=new TestRun();
TR.run();
}
}
并且它还执行 run() 方法并打印 Running Normal Thread
尽管它是在没有单独的 runnable 的情况下构建的!那么这两种方法的主要区别是什么
and it also executes the run() method and prints Running Normal Thread
although it's constructed without a separate runnable! so what's the main difference between the two methods
推荐答案
Thread.run()
不会产生新线程,而 Thread.start()
会,即 Thread.run
实际上与调用者在同一个线程上运行,而 Thread.start()
创建一个新的线程来运行任务.
Thread.run()
does not spawn a new thread whereas Thread.start()
does, i.e Thread.run
actually runs on the same thread as that of the caller whereas Thread.start()
creates a new thread on which the task is run.
这篇关于运行和启动线程的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!