我试图让我的主线程产生一个新线程,并在一段时间后提高中断标志。当它这样做时,生成的线程应该看到该标志并终止自身。

主线程看起来像这样:

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");
}

生成的线程在其代码中散布着以下一堆内容:

if(Thread.interrupted()) return;

当我处于调试模式时,一切都运行良好。中断标志由主线程引发并由生成的线程捕获。但是,在常规运行模式下,无论我设置余量多长时间,生成的线程似乎都没有收到中断标志。

有谁知道我做错了什么?

笔记:我正在使用 Ubuntu,而且对于 Linux 来说我还是个新手。问题可能出在操作系统上吗?我尚未在任何其他操作系统上测试过该代码。

有帮助吗?

解决方案

我建议你考虑使用它是专门做这种事情,可以帮助你在其他方面的ExecutorService的。

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

其他提示

这是我的猜测:

  • 当主线程调用时 t.interrupt(); t 线程已经完成执行。
  • 当主线程调用时 t.interrupt(); 在 t 线程中没有更多的调用来检查 interrupted() 旗帜。
  • 运行代码后出现异常?您是否在“允许”时间后收到在代码中抛出的异常,或者您得到了其他类似的异常 ThreadInterruptedException 或类似的?尝试编写捕获的异常的消息......

你有嵌套Thread.interrupted的检查()?该方法清除中断标志,所以第二调用返回false。你可以使用isInterrupted()来代替。

看起来好像没有在f为达到Thread.interrupted()()调用。

你看到在调试和运行模式下的不同的行为可能是由于竞态条件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top