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.
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.