karl
karl

Reputation: 11

How to "try start" one thread from several other threads, java

I wrote this in my function:

if(myThread.isAlive()) {
} else {
myThread.start();
}

but this is unsafe if many threads call this function the same time. start a running thread throws an exception.

So except putting try-catch around it, do I have other options?

Upvotes: 1

Views: 191

Answers (4)

bestsss
bestsss

Reputation: 12066

contrary on what everyone might tell: do not use isAvile() or getState(), both require to execute them into a sync. block along w/ thread.start() and requires that the thread actually uses itself as monitor (de-facto it does so)

instead, just catch the exception (IllegalThreadStateException) of start() and ignore it.

try{
  thread.start()
}catch(IllegalThreadStateException _x){
//ignore or log the reason, use getState(), if need be
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533750

I would only create the thread when I intend to start it.

What you can do is

synchronized(thread) {
    if(thread.getState() == Thread.State.NEW)
        thread.start();
}

A thread which has finished will not be alive, but it cannot be retstarted.

Upvotes: 1

Anthony Accioly
Anthony Accioly

Reputation: 22471

Use a syncronized method / block? Use locks?

Upvotes: 0

MByD
MByD

Reputation: 137392

Make this method synchronized. Also, this check (isAlive()) is unsafe because if the thread have been finished you cannot start it again (and isAlive() will return false...)

Upvotes: 3

Related Questions