I have an application having a thread which runs continously,writing to a file.And it should terminate on a button click.But this results in flooding of Exceptions which forces the application to terminate.I tried using stop() function,but that doesn't work.Can any one suggest a method(code if possible) to safely terminate the thread and close the file.
Asked
Active
Viewed 168 times
0
-
The safest way is always having the threat terminate itself. I think it maybe a better idea to look into what is causing the exception. Would you mind pasting in the stack trace? – ming_codes Jul 18 '11 at 21:10
2 Answers
1
Threading in Java is cooperative: you can not stop a thread from outside, you can only signal it to stop an then thread stops itself (i.e. exits the run method).
To signal it to stop, just have a boolean field running=true
which thread checks in it's main loop. When running==false
thread exits the run()
method.
In your particular case it could be a bit trickier depending how you read data to be written to file. Do you use any blocking read calls to read the data?

Peter Knego
- 79,991
- 11
- 123
- 154
-
Simple and effective...that did the trick...thks Peter...u saved my day!! – Anva316 Jul 18 '11 at 21:20
0
For the thread:
public void run() {
while (running) {
// write each line to file here
{
// close file
}
For the button's onClick()
add:
running=false;
myThread.join(); // enclose in try/catch and while loop appropriately to ensure the thread ends

pqn
- 1,522
- 3
- 22
- 33