在ExecutorService任务中停止无限循环 [英] Stop an infinite loop in an ExecutorService task

查看:677
本文介绍了在ExecutorService任务中停止无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

class Task implements Callable<String> {
    public String call() throws Exception {
        String s = "initial";
        try {
            System.out.println("Started..");
            /*for (int i=0;i<10000;i++) {
                if (i % 2 == 0) {
                    System.out.println("Even");
                }
            }*/
            boolean flag = true;
            while(flag) {

            }
            System.out.println("Finished!");
            s = "Done";
        }
        catch (RuntimeException e) {
            s = "RuntimeException";
        }
        catch (Exception e) {
            s = "Exception";
        }
        finally {

        }
        return s;
    }
}

public class ExecutorServiceTest {

    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        List<Future<String>> result = executor.invokeAll(Arrays.asList(new Task()), 5, TimeUnit.SECONDS);
        executor.shutdown();
        Iterator<Future<String>> iter = result.iterator();
        while (iter.hasNext()) {
            System.out.println("Came here");
            Future<String> fut = iter.next();
            System.out.println(fut.get());
        }
    }
}

有没有办法我可以阻止线程执行无限循环吗?

Is there a way in which i can stop the thread executing the infinite loop?

推荐答案

是的,你可以替换 flag (或逻辑&& ),带!Thread.currentThread()。isInterrupted()

Yes, you can replace flag (or logically &&) with !Thread.currentThread().isInterrupted().

这样,当任务是取消,循环将被终止。

This way, when the task is canceled, the loop will be terminated.

循环看起来像这样:

while(!Thread.currentThread().isInterrupted() && flag) {
  /* Do work. */
}

使用应该是这样的:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> task = executor.submit(new Task());
String str;
try {
  str = task.get(5, TimeUnit.SECONDS);
} finally {
  task.cancel(true);
}

这篇关于在ExecutorService任务中停止无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆