Reputation: 8702
I got the following error when I try to start again my thread.
Exception in thread "Thread-1" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at com.jrat.server.Server.run(Server.java:159)
Here is the line:
if (!t.isAlive()) t.start();
The code can be executed many times as it is in a loop (socket handler). As far as I know, this error means that it can't start a new Thread because it is already running. What's weird is I have a isAlive before.
Any idea why it is like that?
Thanks.
Upvotes: 3
Views: 3111
Reputation: 172
Vodemki, creating a new thread every time you have a task is expensive. You should use a thread pool. Basically what it does is that you have a pool of n threads and you submit tasks to it. If some thread is free, it will perform your task. If some thread is done with its task, it goes back to the pool waiting for some other task.
Try using ExecutorService for pooling threads.
Upvotes: 1
Reputation: 172
What you are trying to achieve is that if your thread is not alive, start it. But it is conceptually wrong.
You can't call the start method even if your thread is not alive. If you have started it once, you can't start it again even after it has completed its execution.
If what you are intending to do is to re-run a task, then you can try ExecutorService.
Upvotes: 1
Reputation: 8702
I found the easiest way:
Every time I need to start a new Thread, I create a new one:
Thread t = new Thread()
{
public void run()
{
// Do your deal here
}
};
t.start();
Upvotes: 0
Reputation: 142
You can't call start on a Thread that has been started previously. Even if the thread run method has terminated.
Upvotes: 2
Reputation: 1500485
As far as I know, this error means that it can't start a new Thread because it is already running.
No, it means you can't start a thread which has already been started.
You can't restart a thread, which is what you're trying to do. From the documentation for start()
:
Throws: IllegalThreadStateException - if the thread was already started.
You should probably be using an ExecutorService
instead, at a guess - but it's not really clear what you're trying to do.
Upvotes: 8