Ole Ole - 7 months ago 36
Java Question

Stop and restart a already running thread

The Thread should end if I press a button, which sets the isButtonPressed to true.
My problem is, that if a want to start the thread with thread.start(runnable) by clicking the button, I get this: IllegalThreadStateException: Thread already started (I thought the thread was terminated after the break because the the loop is over, but it seems that I am wrong).

Thread thread = new Thread(runnable);
thread.start(runnable);


The runnable Runnable:

Runnable runnable = new Runnable() {
@Override
public void run() {
time = 10;
for (int i = 10; i <= 10; i--) {
handler.post(new Runnable() {
@Override
public void run() {
txt_Time.setText(String.valueOf(time));
}
});

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}

if (isButtonPressed) {
break;
}

if (time == 0) {
resetVisibleState();
break;
} else {
time--;
}
}
}
};


Thanks for your help!

Answer

Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);
Comments