java - 我可以在一个线程中运行一个线程吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11107792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I run a thread within a thread in java?
提问by 2dvisio
In Java I have the necessity of implementing a class that extends Thread within another similar class. Is that possible?
在 Java 中,我需要实现一个在另一个类似类中扩展 Thread 的类。那可能吗?
An example of what I am trying to do is the following (simplified) snippet:
我正在尝试做的一个例子是以下(简化的)片段:
// The first layer is a Thread
public class Consumer extends Thread {
// Variables initialized correctly in the Creator
private BufferManager BProducer = null;
static class Mutex extends Object {}
static private Mutex sharedMutex = null;
public Consumer() {
// Initialization of the thread
sharedMutex = new Mutex();
BProducer = new BProducer(sharedMutex);
BProducer.start();
}
public void run() {
int data = BProducer.getData();
///// .... other operations
}
////// ...... some code
// Also the second layer is a Thread
private class BufferManager extends Thread {
Mutex sharedMutex;
int data;
public BufferManager(Mutex sM) {
sharedMutex = sM;
}
public int getData(Mutex sM) {
int tempdata;
synchronized(sharedMutex) {
tempdata = data;
}
return tempdata;
}
public void run() {
synchronized(sharedMutex) {
data = getDataFromSource();
}
///// .... other operations on the data
}
}
}
The second Thread is implemented directly inside the First one. Moreover I'd like to know if implementing a Mutex like that will work. If not, there's any better (standard) way to do it?
第二个线程直接在第一个线程内部实现。此外,我想知道实现这样的互斥锁是否可行。如果没有,有没有更好的(标准)方法来做到这一点?
Thank you in advance.
先感谢您。
回答by nicholas.hauschild
The Thread
is not run 'within', but rather side-by-side.
该Thread
不是“中”跑,而是并排侧。
So yes, you can start up another Thread
to run side-by-side with your other two Thread
's. As a matter of fact, any Thread
can start another Thread
(so long as the OS allows it).
所以是的,您可以启动另一个Thread
与其他两个并排运行Thread
。事实上,任何人Thread
都可以启动另一个Thread
(只要操作系统允许)。
回答by user949300
Yes, this should work and the shared Mutex should do it's job. Out of paranoia, I'd make both the mutex declarations final
to avoid any weird "escaping" issues. e.g.
是的,这应该可以工作,共享互斥体应该可以完成它的工作。出于偏执,我会同时声明互斥锁final
以避免任何奇怪的“转义”问题。例如
final Mutex sharedMutex;
One suggestion: maybe this is my style, but for code like this I seldom extend Thread
. Just implement Runnable
instead. IMO it's a bit less confusing (YMMV here). Plus, when you start using advanced concurrency utilities like Executor
, they deal with Runnables
, not Threads.
一个建议:也许这是我的风格,但对于这样的代码,我很少扩展Thread
. 只是实施Runnable
。IMO 不那么令人困惑(YMMV 在这里)。另外,当您开始使用诸如 之类的高级并发实用程序时Executor
,它们处理的是Runnables
,而不是线程。