Reputation: 7709
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?
Upvotes: 0
Views: 1679
Reputation: 7202
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)
.
Upvotes: 2
Reputation: 172
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.
Upvotes: 0
Reputation: 32517
Use some kind of flag (boolean?) to signal your worker thread to stop after finishing what it is processing right now.
Upvotes: 0