为执行run()添加线程中断

时间:2012-10-18 16:49:12

标签: java multithreading executorservice

这个问题是导致它的几个问题的高潮。我只是想确保在我做出任何改变之前我已经做好了一切。

所以这就是我正在使用的数据结构:

在抽象类中:

public abstract void doRun();

public void run(){
    try{
    while(!Thread.currentThread().isInterrupted() || hasRunBefore){
        doRun();
    }
    }catch (InterruptedException e){Thread.sleep(1); System.out.println("Thread Interrupted: "); e.printStackTrace(); }

}

然后在实现我的抽象类的子类中:

public void doRun(){
    doChildClassStuff();
}

然后在我的主要课程中调用这些时,我只需要

 ClassName myClass = new ClassName(constructor.list);
 ExecutorService threadPool = Executors.newFixedThreadPool(12);
    List<Future<?>> taskList = new ArrayList<Future<?>>();
    taskList.add(myClass);
    for(Future future : taskList){
        try{
            future.get(1, TimeUnit.SECONDS);
        }catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace();
        }catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace();
        }catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace();
        }catch(TimeoutException ex) {future.cancel(true);}
    }
    threadPool.shutdown();
    threadPool.awaitTermination(60, TimeUnit.SECONDS);
    threadPool.shutdownNow();

如果thread.sleep()失败,则意味着该线程已被中断并应退出。如果所有线程都需要超过60秒,那么它们都会从awaitTermination发送thread.interrupt()命令,对吗?

我在这里完全偏离基地吗?

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试处理基类中的线程中断。不幸的是,基类没有办法“监听”线程中断。您的doChildClassStuff()需要自行处理Thread.currentThread().isInterrupted()项检查。它需要能够检测线程是否已被中断,以便它可以返回或抛出InterruptedException

您不需要Thread.sleep(1);。如果线程被中断,它将抛出InterruptedException,但您可以轻松地使用Thread.currentThread().isInterrupted()测试该线程。由于你已经进入InterruptedException的阻止区块,我不确定它到底是什么意思。此外,您的doRun()不会抛出InterruptedException,因此代码示例(原样)将无法编译。