4

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!

Raedwald
  • 46,613
  • 43
  • 151
  • 237
jkigel
  • 1,592
  • 6
  • 28
  • 49

2 Answers2

6

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

AurA
  • 12,135
  • 7
  • 46
  • 63
1

From your code slice it seems that you are using a Runnable class with a Thread attribute. Instead of using stop/start you might use suspend/resume below:

private boolean isPaused;

public void run() {
    while (!isRunning) {
        // do your stuff
        while (isPaused) {
            mainThread.wait();
        }
    }
}

public void suspend() {
    isPaused = true;
}

public void resume() {
    isPaused = false;
    mainThread.notify();
}

I did not add the synchronized blocks to keep the code small, but you will need to add them.

Telmo Pimentel Mota
  • 4,033
  • 16
  • 22