In Java ho la necessità di implementare una classe che estende Thread all'interno di un'altra classe simile. È possibile?Posso eseguire un thread all'interno di un thread in java?
Un esempio di quello che sto cercando di fare è il seguente (semplificato) frammento:
// 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
}
}
}
il secondo thread è implementata direttamente all'interno del primo. Inoltre mi piacerebbe sapere se l'implementazione di un Mutex come quello funzionerà. In caso contrario, c'è un modo migliore (standard) per farlo?
Grazie in anticipo.
Questo non è Inception. – mre
.. Come puoi saperlo? – BlackVegetable
Tutti i thread sono avviati da altri thread, non è possibile scegliere. I thread sono per fare il lavoro nel modo più indipendente possibile. –