Can I Run a Thread Within a Thread in Java?
In Java I Have the Necessity of Implementing a Class That Extends Thread Within Another Similar Class. Is That Possible? an Example of What I Am Trying to Do...
In Java I have the necessity of implementing a class that extends Thread within another similar class. Is that possible?
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.
2 Answers
The Thread is not run 'within', but rather side-by-side.
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).
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 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.