gpt4 book ai didi

java - 在 run() 的实现中添加线程中断

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:11 25 4
gpt4 key购买 nike

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

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

在抽象类中:

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 秒,那么它们都会从 waitTermination 发送 thread.interrupt() 命令,对吗?

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

最佳答案

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

您不需要Thread.sleep(1);。如果线程被中断,它将抛出 InterruptedException,但您可以使用 Thread.currentThread().isInterrupted() 轻松测试。由于您已经处于 InterruptedException 的 catch block 中,所以我不确定它的意义是什么。此外,您的 doRun() 不会抛出 InterruptedException,因此代码示例(按目前的情况)不会编译。

关于java - 在 run() 的实现中添加线程中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com