Threading in Java

▼魔方 西西 提交于 2019-12-13 15:26:35

问题


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:


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();



回答2:


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 check interrupted() 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...



回答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:


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.



来源:https://stackoverflow.com/questions/871968/threading-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!