在Java中,如果我调用一个类从另一个可运行对象扩展线程,Thread执行? [英] In Java, if I call a class that extends Thread from another runnable object, which Thread executes?

查看:286
本文介绍了在Java中,如果我调用一个类从另一个可运行对象扩展线程,Thread执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个类Foo扩展Thread,并实现它自己的公共方法称为bar ()以及所需的run()方法。如果我实现了多个Foo对象,每个对象包含对另一个Foo对象的引用,并且在Foo类的run()方法中,对于任何具有引用的Foo对象,都是对bar()方法的调用。如果名为Thread-1的Foo对象调用名为Thread-2的Foo对象上的bar(),那么谁正在Thread-2中执行方法代码?执行是否从Thread-1转移到Thread-2来执行或者Thread-1继续在Thread-2中执行代码?

解决方案

一个新的线程只有在第一个选择你调用 thread.start()(或使用 executor.submit(runnable))。所有其他方法调用仍保留在当前线程中。


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. 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. 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"? Does execution get handed off from "Thread-1" to "Thread-2" to execute or does "Thread-1" continue executing code in "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)). All other method invocations remain in the current thread.

这篇关于在Java中,如果我调用一个类从另一个可运行对象扩展线程,Thread执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆