When the below code is executed it is guaranteed that C will be printed at the end. The output will be either ABC or BAC.
What changes needs to be done to ensure that t2 runs only after execution of t1 ,So the expected output is ABC .
Possible options include
1) set t1 a higher priority than t2.
2) Create threadpool and submit thread t1 to executor and wait for completion using awaitTermination method. Once t1 is
completed proceed with t2.
3) Future object.
4) Countdown latch.
What is the recommended concurrent API class I should use ?.
Anil Kumar wrote:
So the final sequence of starting the threads is T1-->T2-->T3-->Main.
The approach that I was thinking was to use Countdown latch.
Not sure what you mean by "sequence of starting". If that is the order that the threads should start, then you already failed, as the main thread was started first by the JVM.
If you mean that that is the order which should finish, ie. T2 has to wait for T1 to complete before it can complete, then using the join() method would work here. Why not have T2 call join() on the T1 thread object? etc. After all, that is what the join() method was designed for -- to wait for the completion of another thread.
Anil Kumar wrote:So below code snippet will ensure that thread 2 can start only if thread 1 is completed and Main method will be the last method to finish executing.
Well, to be honest, if you are going to wait until a thread has finished before even starting the next one, perhaps it would be a good idea to change the code to not use threads (or limit its use for that portion).
Completely agreed with you,the code is as good as single threaded code. Actually the code snippet that I posted was part of mock test, so I was just figuring out what changes in the code is required to ensure that T1 thread runs to its completion and then T2 executes.Thanks for your help.