gpt4 book ai didi

java - 主 Java 线程终止时如何管理工作线程生命周期?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:29:30 25 4
gpt4 key购买 nike

我想实现以下目标:当我的应用程序启动时,主线程将启动 1+ 个应该在后台运行的工作线程,并定期在后台执行操作。这些不应该阻塞主线程:一旦 main 启动了 workers,它就会继续做自己的事情,直到:

  1. 主线程完成(正常的应用程序终止)——在命令行实用程序的情况下,这是到达 main(String[]) 方法的末尾时;在 Swing GUI 的情况下,可能是在用户选择 File >> Exit 菜单等时。
  2. 操作系统抛出终止命令(SIGKILL 等)
  3. 主线程中发生意外的、未捕获的异常,有效地杀死了它(这只是上面#1 的不礼貌版本)

一旦从主线程启动/提交,我希望所有工作线程(Runnable)本质上都有自己的生命周期,并且独立于主线程存在。但是,如果主线程在任何时候死了,我希望能够阻塞(如果可能的话)主线程,直到所有工作线程都完成关闭,然后然后“允许”主线程线程死亡。

我迄今为止最好的尝试,虽然我知道我到处都漏掉了部分:

public class MainDriver {
private BaneWorker baneWorker;

private ExecutorService executor = Executors.newCachedThreadPool();

public static void main(String[] args) {
MainDriver driver = new MainDriver();
driver.run();

// We've now reached the end of the main method. All workers should block while they shutdown
// gracefully (if at all possible).
if(executor.awaitTermination(30, TimeUnit.SECONDS))
System.out.println("Shutting down...");
else {
System.out.println("Forcing shut down...");
executor.shutdownNow();
}
}

private void run() {
// Start all worker threads.
baneWorker = new BaneWorker(Thread.currentThread());
// More workers will be used once I get this simple example up and running...

executor.submit(baneWorker);
// Eventually submit the other workers here as well...

// Now start processing. If command-line utility, start doing whatever the utility
// needs to do. If Swing GUI, fire up a parent JFrame and draw the application to the
// screen for the user, etc.
doStuff();
}

private void doStuff() {
// ??? whatever
}
}

public class BaneWorker implements Runnable {
private Timer timer;

private TimerTask baneTask;

private Thread mainThread;

public BaneWorker(Thread mainThread) {
super();

this.mainThread = mainThread;
}

@Override
public void run() {
try {
timer = new Timer();

baneTask = new TimerTask() {
@Override
public void run() {
System.out.println("When the main thread is ashes...");
}
};

// Schedule the baneTask to kick off every minute starting now.
timer.scheduleAtFixedRate(baneTask, new Date(), 60 * 1000);
} catch(InterruptedException interrupt) {
// Should be thrown if main thread dies, terminates, throws an exception, etc.
// Should block main thread from finally terminating until we're done shutting down.
shutdown();
}
}

private void shutdown() {
baneTask.cancel();

System.out.println("...then you have my permission to die.");

try {
mainThread.join();
} catch(InterruptedException interrupt) {
interrupt.printStackTrace;
}
}
}

我是在轨道上还是在轨道上?我需要更改什么才能使这项工作按我需要的方式进行?我是 Java 并发的新手,正在尽我最大的努力正确使用并发 API,但有点磕磕绊绊。有任何想法吗?提前致谢!

最佳答案

主线程必须向工作线程发出终止信号(通常这仅通过使用标志来实现),然后它应该在每个线程上调用 join 以等待它们终止。在这里看看:Java: How to use Thread.join

关于java - 主 Java 线程终止时如何管理工作线程生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17472780/

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