简体   繁体   English

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. 注意:我正在使用Ubuntu,对所有Linux都是全新的。 Can the problem be with the OS? 问题可能出在操作系统上吗? I have not tested the code on any other OS. 我尚未在任何其他操作系统上测试过该代码。

Here are my guesses: 这是我的猜测:

  • When main thread calls t.interrupt(); 当主线程调用t.interrupt(); the t thread has already finished execution. t线程已经完成执行。
  • When main thread calls t.interrupt(); 当主线程调用t.interrupt(); in the t thread there are no more calls to check interrupted() flag. 在t线程中,不再有任何调用来检查interrupted()标志。
  • 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? 您是否在“允许”时间过后在代码中抛出了异常,还是得到了诸如ThreadInterruptedException类的其他东西? Try writing the message of the caught exception... 尝试编写捕获到的异常的消息...

It looks as though the Thread.interrupted() call is not being reached in f(). 似乎在f()中未到达Thread.interrupted()调用。

The different behaviour you are seeing in Debug and Run modes is likely to be due to a race condition. 您在“调试”和“运行”模式下看到的不同行为很可能是由于竞争条件造成的。

Do you have nested checks of Thread.interrupted()? 您是否嵌套了Thread.interrupted()检查? That method clears the interrupted flag, so the second call returns false. 该方法清除了中断的标志,因此第二次调用返回false。 You could use isInterrupted() instead. 您可以改为使用isInterrupted()。

I suggest you consider using an ExecutorService which is designed to do this sort of thing and could help you in other ways. 我建议您考虑使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM