Java stream error. Launch IllegalThreadState is already running

Whenever I start my thread, I always do this check. I did not find anywhere what I called start on thread without checking below

if (!myThread.isAlive()) myThread.start(); 

However, I am ending IllegalThreadStateException: Thread is already running. This is actually a failure of my application (android). So, is there some other check I need to do before starting the thread?

+7
source share
3 answers

You should check if the thread has already started using getState () and start it only if its state is NEW , otherwise create a new thread (if necessary).

+11
source

Are you creating a new instance for the myThread link using the new one? You can only execute myThread.start () once in a single instance.

Checking if he is alive is not the right way. Create a new instance.

+3
source

I just had a similar case, so I give a later answer.

The problem is that your solution with Thread.isAlive() and Thread.start() not multithreaded. It may happen that the first thread calls your code, executes isAlive() and somewhere inside Thread.start() , after a new thread has been started and before its state has been changed, a task switch appears, and the second one calls executes isAlive() when it is still false , causing start() called twice. To make it worse somewhere inside start() , it seems that the task switch is forced and therefore this problem occurs quite often.

Decision. Override start() to make it multithreaded, e.g.

 private final AtomicBoolean started = new AtomicBoolean(false); /* (non-Javadoc) * @see java.lang.Thread#start() */ @Override public synchronized void start() { if (!started.getAndSet(true)) { super.start(); } } 

Then your problem will no longer appear, even if start() accidentally called twice.

0
source

All Articles