0

Assume,I have thread T1, T2 and T3, how will I ensure that thread T2 run after T1 and thread T3 run after T2?

3
  • 2
    Assuming 'run after' means 'T2 runs after completion of T1', do you need threads? If not, the question is not clear :)
    – Vikdor
    Sep 21, 2012 at 19:01
  • Is that start after each other, or is it that T1 must finish before T2 starts and same for T3 ? In that case you might as well run sequentially. Sep 21, 2012 at 19:01
  • I never understand these questions. If you want sequential execution, why are you using threads at all?
    – user207421
    Sep 21, 2012 at 21:40

5 Answers 5

3

The solution to your problem is probably "don't use multiple threads." If you want to ensure that action 2 executes after action 1, and action 3 executes after action 2, with no interleaving, then the solution is to execute action 1, then execute action 2, then execute action 3. Threads are useful as a mechanism for parallelism, and by trying to make sure that the actions run in a specific order you are explicitly disallowing parallelism. Don't try to use a mechanism to do the exact opposite of the thing it was designed to do.

3

You will have to start T2 after T1 dies.

t1.start();
t1.join();
t2.start();

And actually, if you need to run them sequentially, you probably don't/shouldn't need to put them in separate threads. Just put the t1 and t2 code sequentially in one thread.

0

Take a look at Thread#join():

Waits for this thread to die.

0

You can design this with

  1. CountDownLatch
  2. Wait-NotifyAll
  3. Observer-observable pattern.
0

Start T2 at the end of T1 code. Start T3 at the end of T2 code.

Or just run the functions sequentially in one thread, as suggested by the other posters, since this exercise is essentially pointless.

Not the answer you're looking for? Browse other questions tagged or ask your own question.