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.
The
Threadis not run ‘within’, but rather side-by-side.So yes, you can start up another
Threadto run side-by-side with your other twoThread‘s. As a matter of fact, anyThreadcan start anotherThread(so long as the OS allows it).