Reputation: 8985
I have a multi threaded console application which runs endlessly. Right now I use ctrl-c to end it, but sometimes it causes the finally block not to be called and leaves some processes that the original program started to run even after the main java program has ended.
I found this answer on Stackoverflow
https://stackoverflow.com/a/3194586/492015
class MyThread extends Thread
{
volatile boolean finished = false;
public void stopMe()
{
finished = true;
}
public void run()
{
while (!finished)
{
//do dirty work
}
}
}
But since my program is console based, how would this apply? I would need to make the program wait for keyboard inputs? so if I press 'q' for example stopMe() would get called. How would I have to do this?
Upvotes: 0
Views: 53
Reputation: 138
If you want to clean up, you might want to consider a shutdown hook. See: Java shutdown hook
Upvotes: 0
Reputation: 100219
If you want to perform clean-up, you can register a shutdown hook:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// do the cleanup
}
});
According to my experience it's always executed when Ctrl+C is pressed.
Upvotes: 1