0

i have a main thread in my app and inside this main thread i create another thread, let's say it is named named "WorkerThread". The WorkerThread has an infinite loop that does some database search and eventually communicates via Serial Port with a thermal printer. But when the user closes the application, it remains alive because the thread is still running. I know i can just set my thread as daemon, which means the thread will stop when the application closes, but also i know that this may cause IO errors. So, what is the most efficient way of achieving this behavior in a non-daemon thread?

Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101
  • Could you use `Task`s instead? You can then tell the executor to stop all the tasks. – Djon Aug 14 '14 at 12:14

3 Answers3

2

Add the boolean flag to stop your thread on application exit.

public class WorkerThread extends Thread {

    private boolean running = false;

    @Override
    public void run() {
        while (running) {
            // do smth
        }
    }

    @Override
    public void start() {
        setRunning(true);
        super.start();
    }

    @Override
    public void setRunning(boolean value) {
        this.running = running;
    }
}

To stop the thread, call workerThread.setRunning(false).

SeniorJD
  • 6,946
  • 4
  • 36
  • 53
  • That's what i thought as the best solution, but when do i call the setRunning(false)? I don't have control over the application closing, it is the user who closes it by closing the main window. – Mateus Viccari Aug 14 '14 at 12:17
  • 2
    Add the `WindowListener` to your main window and listen to `windowClosing` **AND** `windowClosed` methods – SeniorJD Aug 14 '14 at 12:19
  • Or use the `shutdown hook thread` http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java – SeniorJD Aug 14 '14 at 12:20
  • You should mark the flag as `volatile`, or use an `AtomicBoolean` – James_D Aug 14 '14 at 13:12
  • Well, if you [`setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation(int)) on a JFrame, you don’t have to worry about whether the other threads are daemon or not… – Holger Aug 14 '14 at 13:25
0

Use some kind of flag (boolean?) to signal your worker thread to stop after finishing what it is processing right now.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

You should interrupt it from the main thread using Thread.interrupt(). In the worker thread, on each loop iteration, it should check for the return of workerThread.interrupted() and if it is true then clean up and return.

Check the documentation, cause blocking methods like wait() will throw an InterruptedException you might have to evaluate.

fmcato
  • 172
  • 1
  • 12