gpt4 book ai didi

Java线程执行器永远不会关闭?

转载 作者:行者123 更新时间:2023-11-30 06:09:24 24 4
gpt4 key购买 nike

我有以下代码,将一些数据放入阻塞队列,并基于固定线程池将线程任务提交给 Java 执行程序服务。当我尝试关闭执行程序但它没有关闭时,有什么想法吗?

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadExecutir {
public static ArrayBlockingQueue<String> files;

public static void main(String[] args) {
// TODO Auto-generated method stub
shutdownExec();
}

private static void shutdownExec() {
int size = 10;
files = new ArrayBlockingQueue<String>(100);
for (int i = 0; i < 5; i++) {
files.add("Java " + i);
}

ThreadExecutir outer = new ThreadExecutir();
ExecutorService executor = Executors.newFixedThreadPool(size);
for (int i = 0; i < 3 * size; i++) {
executor.submit(outer.new myThread());
}
System.out.println(executor.isShutdown());
executor.shutdown();

try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
System.out.println("Awaiting for threads to complete!");
} catch (InterruptedException e) {
e.printStackTrace();
}
if (files.isEmpty())
executor.shutdownNow();
System.out.println(executor.isShutdown());

}

class myThread extends Thread {
public void run() {

String threadName = Thread.currentThread().getName();
System.out.println("Thread " + threadName + "started running! ");
try {
String uploadThis = files.take();
System.out.println("I'm working " + threadName + " "
+ uploadThis);
// this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Thread " + threadName
+ " finished running! ");
}
}
}
}

最佳答案

在几个 myThread 实例消耗完 files 中的所有元素后,剩余的 block 在 files.take() 上。

shutdown 的 javadoc州

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

在调用 shutdown 之前,您已经提交了所有 30 个任务(其中 10 个正在执行)。所以他们都需要在 ExecutorService 被认为终止之前完成执行。但是它们中的大多数无法完成执行,因为目前没有任何东西可以让它们在 take() 处停止阻塞。

您需要向 ArrayBlockingQueue 提交更多项或中断 ExecutorService 中的线程。 shutdownNow可用于中断这些线程。

请注意,中断可能不足以停止您的线程,因为中断可能在阻塞调用之前到达。你需要更多 sophisticated solution, like a poison pill .


虽然你继承了Thread

class myThread extends Thread {

您仅将 myThread 用作 Runnable(Thread 实现 Runnable)。这是毫无意义的。只需实现 Runnable

class myThread implements Runnable {

关于Java线程执行器永远不会关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978442/

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