0
votes

I'm trying to run a list of threads from a main, where one of them, let's call it tLast, should be started individually after the others entered waiting state. I know about t.join but as I understand it works only if the thread finishes it's work, and as I understand waiting doesn't count. So far I tried this, after starting all threads but tLast:

boolean inSleepState = false;
while(!inSleepState){
    inSleepState = true;
    for(Thread thread: threads){
        if(thread.checkState != Thread.state.WAITING){
            inSleepState = false; 
            break;
        }
    }
}

tLast.start()

The main problem I see with this is that this is a busy wait, which is bad practice and ill adviced as far as I know, But I can't think of another way to do this. Btw I realise I can wait for each thread Individually and spare iteration over threads, but either way this is a busy wait.

1
You're probably looking for a CountDownLatch.chrylis -cautiouslyoptimistic-
Please read tag info before tagging. Not all library routines have tags. Please tag by clicking on a tag choice to see info & avoid typos.philipxy
Is it possible to have your threads notify() an object when they reach their waiting state?anotherAlex154
I dont really see why you would want that, but if your threads are in waiting state i hope its waiting on some object , be it timed-waiting or normal waiting , you could call latch.countDown(); on each thread and then call latch.await(); before calling tLast.start()amarnath harish

1 Answers

1
votes

The join method will only join with a thread after it has terminated. A thread in WAITING state is not terminated.

So the direct answer is that you can't join a waiting thread.

But on the other hand, Thread::join doesn't do a busy wait.

The third thing to note is that relying on a thread's state to indicate something is rather crude. If a thread is WAITING state, that tells you that it is waiting for a notify on some mutex. It doesn't tell you which mutex it is using.

Now ... presumably ... you want your tLast thread to wake up when the other threads reach a specific state. If that is what you are trying to achieve, a CountdownLatch, Semaphore or CyclicBarrier may be what you need.