問題描述
Java中的線程 (Threading in Java)
I am trying to have my main thread spawn off a new thread and, after some time, raise the interrupt flag. When it does so, the spawned thread should see that flag and terminate itself.
The main thread looks something like this:
final Thread t = new Thread()
{
@Override
public void run()
{
f();
}
};
t.start();
try
{
t.join(time);
t.interrupt();
if(t.isAlive())
{
t.join(allowance);
if(t.isAlive())
throw new Exception();
}
}
catch(Exception e)
{
System.err.println("f did not terminate in the alloted time");
}
And the spawned thread has a bunch of the following scattered throughout its code:
if(Thread.interrupted()) return;
When I am in debug mode, everything works perfectly. The interrupt flag is raised by the main thread and is caught by the spawned thread. However, in regular run mode the spawned thread doesn't seem to receive the interrupt flag, no matter how long I set the allowance.
Does anyone know what I am doing wrong?
Note: I am using Ubuntu and I am all‑together new to anything Linux. Can the problem be with the OS? I have not tested the code on any other OS.
‑‑‑‑‑
參考解法
方法 1:
Here are my guesses:
- When main thread calls
t.interrupt();
the t thread has already finished execution. - When main thread calls
t.interrupt();
in the t thread there are no more calls to checkinterrupted()
flag. - You get the exception as a result of running the code? Do you get the exception you throw in your code after "allowance" time or you got some other like
ThreadInterruptedException
or similar? Try writing the message of the caught exception...
方法 2:
It looks as though the Thread.interrupted() call is not being reached in f().
The different behaviour you are seeing in Debug and Run modes is likely to be due to a race condition.
方法 3:
Do you have nested checks of Thread.interrupted()? That method clears the interrupted flag, so the second call returns false. You could use isInterrupted() instead.
方法 4:
I suggest you consider using an ExecutorService which is designed to do this sort of thing and could help you in other ways.
ExecutorService service = Executors.newCachedThreadPool();
Future<ResultType> future = service.submit(new Callable<ResultType() {
public ResultType call() throws Exception {
// do soemthing
return (ResultType) ...;
}
);
// do anything you like until you need to result.
try {
ResultType result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException timedOut) {
// handle exception
// cancel the task, interrupting if still running.
result.cancel(true);
} catch (ExecutionException taskThrewAnException) {
// handle exception
}
// when you have finished with the service, which is reusable.
service.shutdown();
(by user108088、emirc、Matthew Murdoch、Stephen Denne、Peter Lawrey)