gpt4 book ai didi

java - Executor Service 设置标志以停止线程

转载 作者:行者123 更新时间:2023-11-30 10:29:34 27 4
gpt4 key购买 nike

我正在运行简单的线程,它的运行方法如下

public run()
while(!stopFlag){
// print something Line 1
// print something Line 2
// print something Line 3
// print something Line 4
}

如果我通过ExecutorService 运行这个线程

ExecutorService exs = Executors.newFixedThreadPool(5);
exs.execute(new MyThread));

我停止了 ExecutorService

exs.shutdown();

但这不会停止线程,因为标志未设置为 false。在 another question related to same topic我被要求正确处理调用 exs.shutdown() 时引起的 InterruptedException。但在这种情况下,我不会执行任何可能引发 InterruptedException 的操作。

处理这种情况的标准方法是什么?

进一步的问题Sabir 给出的回答是“如果您的可运行对象不能很好地响应中断,除了关闭 JVM 之外,没有什么可以阻止它。”。这似乎是我的情况。

但是如何引入InterruptedException的处理;如果我没有调用任何抛出中断异常的方法?

最佳答案

如果您愿意关闭您的线程,即使该标志保持为真,您应该使用 - ExecutorService.shutdownNow() 方法而不是 ExecutorService.shutdown()

引用自 Java 文档,

关机()

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.

This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt, so any task that fails to respond to interrupts may never terminate.

对于标准方式,我将从 ExecutorService 接口(interface)的 JDK 示例中引用,

使用示例

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool factory method:    class NetworkService implements Runnable {    private final ServerSocket serverSocket;    private final ExecutorService pool;

public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize); }

public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
} } }

class Handler implements Runnable { private final Socket socket; Handler(Socket socket) { this.socket = socket; } public void run() {
// read and service request on socket } }} The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks: void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); // Disable new tasks from being submitted try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
} } catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt(); } }}

请注意,即使使用 shutdownNow() 也无法保证。

编辑: 如果我将您的 while(!stopFlag) 更改为 while(!Thread.currentThread().isInterrupted()) 那么具有条件循环的线程通过 shutdownNow() 关闭,但通过 shutdown() 无法关闭,因此线程通过 shutdownNow() 中断。我在 JDK8 和 Windows 8.1 上。我确实必须在主线程中 hibernate ,以便服务有时间设置服务并启动可运行的。线程启动,进入 while 然后在调用 shutdownNow() 时停止。我没有通过 shutdown() 得到这种行为,即线程永远不会退出 while 循环。因此,通过检查标志或处理异常,让您的可运行对象负责中断的方法应该存在。如果您的 runnable 不能很好地响应中断,除了关闭 JVM 之外,没有什么可以阻止它。

显示了一种好的方法 here

关于java - Executor Service 设置标志以停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43993505/

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