Reputation: 1
Sorry if this is a stupid question. I found a solved problem in a book, but the solution doesn’t contain a source code. I proposed a code, but I’m not sure if the code fits the solution specifications. Please correct the code or propose a better code if possible (explanations are welcome). Thanks for the help.
Problem :
There are three threads T1, T2 and T3. How do you ensure sequence T1, T2, T3 in Java?
Solution :
Sequencing in multi-threading can be achieved by different means but you can simply use join() method of thread class to start a thread when another one is finished its execution. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2.join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last.
Proposed code :
final Thread t3 = new Thread(new T3()); // assume T3 is a Runnable
final Thread t2 = new Thread(new T2());
final Thread t1 = new Thread(new T1());
t3.start();
t2.start();
t1.start();
t2.join();
t1.join();
Upvotes: 0
Views: 2840
Reputation: 216
In your example main thread will wait until execution of t2 and t1 is completed. Sequence of execution of these 3 threads could be different. I beleive that you want to start every thread after execution of the previous one is completed. In this case, I don't see the point of using parallelism. If you want to wait until execution of multiple threads is completed I could suggest you to read about barrier synchronization and especially this class
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html
Upvotes: 1
Reputation: 269807
Your proposed code won't work. t3
could finish before t2
even starts. To guarantee they run in sequence, you need to to this:
final Thread t3 = new Thread(new T3()); // assume T3 is a Runnable
final Thread t2 = new Thread(new T2());
final Thread t1 = new Thread(new T1());
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
But then using multiple threads is pointless and wasteful. You would achieve the same effect with a single thread:
new T1().run();
new T2().run();
new T3().run();
Upvotes: 4