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.
All threads are started by other threads, you don't have a choice. Threads are for doing work as independently as possible.
You can use delegate, for example. Show activity on this post. It'll be executed on the main thread, since it's that thread that calls the method. If you want dosomething to run in the separate thread, have it called within run() and store the result in a myThread field for later retrieval.
Overview. Multi-thread programming allows us to run threads concurrently, and each thread can handle different tasks. Thus, it makes optimal use of the resources, particularly when our computer has a multiple multi-core CPU or multiple CPUs.
Threads don't nest within each other - threads belong to a process. So if you have threads A & B, and then they each create C & D, C & D don't belong to A & B - they belong to your process. So yes, creating additional threads from background threads is acceptable.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With