Can I start a thread in a thread in java?

In Java, I have a need to implement a class that extends Thread in another similar class. Is it possible?

An example of what I'm 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 stream is implemented directly inside the first. Moreover, I would like to know if the implementation of Mutex will be implemented. If not, is there a better (standard) way to do this?

Thanks in advance.

+7
source share
2 answers

Thread does not start "inside", but rather side by side.

So, you can run another Thread to work side by side with two other Thread . In fact, any Thread can run another Thread (as long as the OS allows it).

+18
source

Yes, this should work, and the common Mutex should do the job. From paranoia, I would make mutex final declarations to avoid any weird "screening" problems. eg.

 final Mutex sharedMutex; 

One suggestion: perhaps this is my style, but for such code I rarely extend Thread . Just use Runnable instead. IMO this is a little less confusing (YMMV here). Also, when you start using advanced concurrency utilities such as Executor , they deal with Runnables , not Threads.

+5
source

All Articles