开发者

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

开发者 https://www.devze.com 2023-03-05 16:27 出处:网络
I wrote this in my function: if(myThread.isAlive()) { } else { myThread.start(); } but this is unsafe if many t开发者_开发技巧hreads call this function the same time. start a running thread throws

I wrote this in my function:

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

but this is unsafe if many t开发者_开发技巧hreads 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?


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


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.


Use a syncronized method / block? Use locks?


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消