• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to ensure threads sequence?

 
aqas qaqz
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 can't come up with the code corresponding to the solution of the problem because I still do not understand the solution (especially the bolded text). Please can anyone propose a code that exactly meets the solution specifications (explanations are welcome). Thanks for the help.
_____________________________________________
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.
_____________________________________________
Problem:
There are three threads T1, T2 and T3. How do you ensure sequence T1, T2, T3 in Java?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35709
410
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In trying to write the code, you need to create the three Threads. Then you need to call start() in a specific order. Can you write that much?
 
Tushar Goel
Ranch Hand
Posts: 931
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:In trying to write the code, you need to create the three Threads. Then you need to call start() in a specific order. Can you write that much?


I tried to run 3 thread one after another but it doesn't make sure that it always print in same order. ex:




Output:

Printing 2
Printing 1
Printing 3
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Tushar Goel
Ranch Hand
Posts: 931
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have used join but i think Jeanne asked to write without using join.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have used join but i think Jeanne asked to write without using join.


The question from aqas qaqz asks for the code for a solution specifically with join ...

Please can anyone propose a code that exactly meets the solution specifications


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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!