Java线程 [英] Threading in Java

查看:86
本文介绍了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.

主线程看起来像这样:

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?

注意:我正在使用Ubuntu,对所有Linux都是全新的.问题可能出在操作系统上吗?我尚未在其他任何操作系统上测试过该代码.

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.

推荐答案

我建议您考虑使用ExecutorService,该服务旨在执行此类操作并可以通过其他方式为您提供帮助.

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

这篇关于Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆