1

这个问题是导致它的几个问题的高潮。我只是想确保在我提交我所做的任何更改之前一切都正确。

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

在抽象类中:

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() 命令,对吗?

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

4

1 回答 1

1

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

你不需要Thread.sleep(1);. 如果线程已被中断,它将抛出一个InterruptedException,但您可以Thread.currentThread().isInterrupted()轻松地测试它。由于您已经处于一个捕获块中InterruptedException,因此我不确定它的重点是什么。此外,您doRun()不会抛出InterruptedException代码示例(就目前而言)不会编译。

于 2012-10-18T16:52:44.277 回答