Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for the start of a thread in java

I have a litte race condition in my current android instrumentation test. What I want is:

  1. T1: Start Thread T2
  2. T2: Do something
  3. T1: Join with T2

With step 1 and 3 being Android live cycle events. But because in the instrumentation test everything happens very fast I get:

  1. T1: Start Thread T2
  2. T1: Join with T2 (which turn out to be a no-op)
  3. T2: Do something

Sure I could add a few sleeps to get the desired behaviour but I wonder if there is better way to do it. i.E. is there a way to make sure the thread which was just start ()-ed did actually start for good and is not still sitting in some scheduling queue awaiting start-up.

(Andy boy, do I miss Ada's rendezvous based multitasking)

And to answer mat's question:

  if (this.thread != null && this.thread.isAlive ())
  {
     this.stop.set (true);

     try
     {
        this.thread.join (1000);
     }
     catch (final InterruptedException Exception)
     {
        android.util.Log.w (Actor.TAG, "Thread did not want to join.", Exception);
     } // try
  } // if

As I said: no-op when because the thread has not started yet.

like image 726
Martin Avatar asked Apr 24 '11 14:04

Martin


1 Answers

I typically use a CountDownLatch e.g. see this answer on testing asynchronous processes.

If you want to synchronise the starting of many threads you can also use a CyclicBarrier.

like image 150
Martin Avatar answered Nov 10 '22 07:11

Martin