Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't restart thread [duplicate]

I have the following thread:


public void start() {
        isRunning = true;

        if (mainThread == null) {
            mainThread = new Thread(this);
            mainThread.setPriority(Thread.MAX_PRIORITY);
        }

        if (!mainThread.isAlive()) {
            try {
                mainThread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

At some point I want to stop it's operation:


public void stop() {
        isRunning = false;
        System.gc();
}

When calling start() again the following exception is thrown:

java.lang.IllegalThreadStateException

Pointing the mainThread.start() line of code.

What is the best way to start/stop a thread? how can I make this thread reusable?

Thanks!

like image 543
jkigel Avatar asked Mar 23 '23 20:03

jkigel


1 Answers

Once a thread stop you cannot restart it in Java, but of course you can create a new thread in Java to do your new job.

The user experience won't differ even if you create a new thread or restart the same thread(this you cannot do in Java).

You can read the website for API specification http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html

What you might be looking for is Interrupts. An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

To know more about interrupts read the Java tutorial guide http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

like image 134
AurA Avatar answered Mar 30 '23 00:03

AurA