Posted By:
Robert_Lybarger
Posted On:
Friday, July 28, 2006 07:52 PM
I'll repeat the other guy...format your code properly and preview it before you post it. I'm not going to bother reading the details of the code, but I am guessing you are asking this: "you are doing an operation that might not return a result... so you need a way to handle getting a result or not. The answer here is going to be a timer thread (in addition to whatever thread(s) you have setup to do the actual work).
In fact, the java API finally added a convenience class (TimerTask?) to take care of this, but creating your own isn't a big deal. If you do, I'd recommend this: (1) create an interface named MyTimerListener and have it declare a method called "timeExpired()". (2) create a new class which extends Thread and which takes (and stores) a MyTimerListener object in its constructor; its run() method should just be a sleep call... you pick how long it sleeps. (3) the class in which you are calling the working thread (that might or might not return) should implement MyTimerListener... its implementation of timeExpired() method should just call interrupt() on the working thread. (4) start a thread for your timer first then start the working thread as you are doing. The idea then is that, when your chosen time out has expired, your main thread gets notified and it just stops waiting around on the working thread.
It goes without saying that you should NOT join() on either of those threads from the main program thread. You should put the main program thread into a loop that sleeps a short while (fraction of a second) and checks to see if the working thread is still alive. if it is, do the loop again (sleep and then check). If not, interrupt the timer thread and deal with the output you are wanting to receive.