An enhancement I'm working on requires me to execute sequential lines of time-consuming code in a separate thread so that the user has the ability to terminate that particular task.
Now, since I an not using a loop, I cannot use the time-tested "checking- for-a-flag" method to terminate the thread. Also, the javadocs recommend not using the stop() or suspend() functions.
Is there any other way to stop the thread?
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
Ugly, but I've done it before ...
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Varghese Paul
Greenhorn
Joined: Aug 02, 2004
Posts: 14
posted
0
Thanks everybody.
This was the solutions that came to mind, but I didn't want to do it because it was very ugly, very unsightly and seems a very inelegant way of doing it.
Is there any Exception which could interrupt the execution-flow? Or is it possible to adapt InterruptedException to handle this situation? How do the sleep() or wait() functions throw the InterruptedException?
vu lee
Ranch Hand
Joined: Apr 19, 2005
Posts: 189
posted
0
What are the long operation doing? Some threads can be stopped, but the others can't. If the long-running thread is waiting for a inputstream form a socket, close the socket. If it is waiting for resultset, hm..hmm. ??? One way to do this is to create a job wrapper which will sleep for sometime, then wake up to check whether the job has been done or user wants to cancel the job. If it's done, return. If the user wants to cancel, interrupt the long-running thread.
This is the code sample
public class ThreadHander {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LongRunningJobWrapper longRunningJob = new LongRunningJobWrapper(); Thread thread = new Thread(longRunningJob); thread.start(); try{ Thread.sleep(500); //waiting up to haft of a second longRunningJob.setStillWaiting(false);