Ole Ole - 1 year ago 96
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);

The runnable Runnable:

Runnable runnable = new Runnable() {
public void run() {
time = 10;
for (int i = 10; i <= 10; i--) {
handler.post(new Runnable() {
public void run() {

try {
} catch (InterruptedException e) {

if (isButtonPressed) {

if (time == 0) {
} else {

Thanks for your help!

Answer Source

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();