There is a thread which calls just ONE METHOD.
The problem is the method can work for 1 sec to more than 10minutes.
I have to stop if the thread work for more than 10 secs and I don't have
the source of the method - but, I have to use the method.
Thread.stop() method is deprecated..
So, I tried using interrupt() method, but it did not work.
Then how can the thread be stopped without using stop() ??
I'll agree with Chris here, there really is no way to stop the thread.
However maybe you don't actually need to stop it. Depending on what
it's doing, maybe it's sufficient to stop waiting for the results of
the operation (and let the thread finish on its own). After your
timeout, simply accept that the operation has taken too long and get
on with whatever else you're doing.
The following is completely untested:
public class MyRunnable {
private resultType result = null;
/* perform some long operation */
public void run() {
setResult(sometimesReallyLongOperation());
}
/* set result, notify waiting thread if any */
private synchronized void setResult(resultType result) {
this.result = result;
notify();
}
/* wait at most timeout ms for result */
public synchronized resultType getResult(long timeout) throws MyTimeoutException {
long now = System.currentTimeMillis();
long stop = now + timeout;
while ((result == null) && (stop > now )) {
wait(stop - now);
now = System.currentTimeMillis();
}
if (result == null) {
/* alternative: return default value instead of exception */
throw new MyTimeoutException("gurgle");
}
return result;
}
}
In the main program:
resultType result = null;
Runnable r = new MyRunnable(foo);
Thread t = new Thread(r);
t.start();
try {
result = r.getResult(10000); // wait max 10 seconds
}
catch (MyTimeoutException e) {
System.out.println("operation timed out");
}