本文介绍了如果我们直接调用run方法会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个"TestRunnable"类,它通过实现Runnable
覆盖了run方法.运行覆盖的运行方法,如下所示:
I have a class "TestRunnable" which overrides run method by implementing Runnable
.Running overridden run method, as follow :
TestRunnable nr = new TestRunnable();
Thread t = new Thread(nr);
t.setName("Fred");
t.start();
- 如果我直接拨打
t.run();
该怎么办 - 如果我们不拨打
t.start();
会发生什么? - What if i directly call
t.run();
- What happen if we don't call
t.start();
?
推荐答案
run
方法只是另一种方法.如果直接调用它,那么它将不在另一个线程中执行,而是在当前线程中执行.
The run
method is just another method. If you call it directly, then it will execute not in another thread, but in the current thread.
这是我的考试TestRunnable
:
class TestRunnable implements Runnable
{
public void run()
{
System.out.println("TestRunnable in " + Thread.currentThread().getName());
}
}
仅调用start
时的输出:
TestRunnable in Fred
仅调用run
时的输出:
TestRunnable in main
如果未调用start
,则创建的Thread
将永远不会运行.主线程将完成,Thread
将被垃圾回收.
If start
isn't called, then the Thread
created will never run. The main thread will finish and the Thread
will be garbage collected.
如果两者都不被调用,则输出:(无)
Output if neither is called: (nothing)
这篇关于如果我们直接调用run方法会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!