I have a password saving program that saves passwords to a text file. The user can add or delete passwords and the data will be re-written to the text file. To prevent the program from being really slow, I create a new thread every time the program needs to save. I have a class that extends Thread and will write all data to the text file specified. The problem I am having is when I try to save all data before the user wants to quit. When the quit button is pressed I create a new thread to save the data and then call the System.exit() function to quit.
Thread t = new SaveThread();
t.start();
System.exit(0);
I have noticed that the program will quit before the thread completes. Is there any way that I can tell java to only quit when my thread has stopped running?
You have three options:
t.join()after you start the threadt.run()instead oft.start()Runtime.addShutdownHook.Option 1
This one is easy:
Option 2
Also easy:
Option 3
Also easy, but is done when your application is starting. In your app initialization code, do this:
And it will run automatically when the application is closing.