[英]In Java, if I call a class that extends Thread from another runnable object, which Thread executes?
I am working on some concurrency programming and one part is bothering me. 我正在进行一些并发编程,一部分使我感到困扰。
Let's say I have some class Foo
that extends Thread and implements it's own public method called bar()
as well as the required run()
method. 假设我有一些
Foo
类,它扩展了Thread并实现了它自己的名为bar()
的公共方法以及所需的run()
方法。 If I implement multiple Foo
objects, each one containing a reference to another Foo
object, and inside the run()
method for the Foo
class is a call on the bar()
method for whatever Foo
object it has a reference to. 如果我实现了多个
Foo
对象,则每个对象都包含对另一个Foo
对象的引用,并且在Foo
类的run()
方法内部是对bar()
方法的调用,以引用其引用的任何Foo
对象。 If the Foo
object with name " Thread-1
" calls bar()
on the Foo
object with name " Thread-2
", then who is actually executing the method code in " Thread-2
"? 如果
Foo
名称为“对象Thread-1
”呼吁bar()
上Foo
对象名称为“ Thread-2
”,那么谁是实际执行中“方法代码Thread-2
”? Does execution get handed off from " Thread-1
" to " Thread-2
" to execute or does " Thread-1
" continue executing code in " Thread-2
"? 是将执行从“
Thread-1
”切换到“ Thread-2
”以执行还是“ Thread-1
”继续执行“ Thread-2
”中的代码? If it is the second choice, how can I make it act like the first choice? 如果是第二选择,我该如何使其像第一选择?
A new thread is started only if you invoke thread.start()
(or use executor.submit(runnable)
). 仅当您调用
thread.start()
(或使用executor.submit(runnable)
)时,才会启动新线程。 All other method invocations remain in the current thread. 所有其他方法调用均保留在当前线程中。
Foo
is just an object, imagine it does not extends Thread
, what would you expect? Foo
只是一个对象,想象它没有扩展Thread
,您会期望什么? As long as new thread is not start()
ed, you are just calling an ordinary method, on behalf of the calling thread. 只要没有
start()
新线程,就代表调用线程在调用普通方法。
Moreover, if calling a method on a different Thread
object would cause that thread taking over the execution, what would happen with the current thread's execution? 而且,如果在不同的
Thread
对象上调用方法会导致该线程接管执行,那么当前线程的执行将如何处理?
Apart from being executed when you start the thread, run()
is a normal method. 除了在启动线程时执行之外,
run()
是一种常规方法。 If you manuallly call, it behaves like any other method, meaning it is executed inside the caller's thread. 如果您手动调用,则它的行为与其他任何方法一样,意味着它在调用者的线程内执行。
It will run on the thread that called it. 它将在调用它的线程上运行。 Calling a method in a class that extends thread is no different than calling a method of any other class.
在扩展线程的类中调用方法与调用任何其他类的方法没有什么不同。
public class A extends Thread
{
public void bar()
{
System.out.println(Thread.currentThread().getName());
}
public void run()
{
new A().bar();
}
public static void main()
{
A testA = new A();
testA.setName("parent");
testA.start();
}
}
Should print 'parent'; 应打印“父母”;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.