java - Executors.newFixedThreadPool 如何停止同步方法上的所有 Activity 线程

标签 java multithreading executorservice synchronized

我有一个执行器服务,它可以同时提交 x 个线程来执行一项长任务。我需要能够停止所有当前正在运行的线程并防止排队任务启动。我正在尝试实现一种方法来处理正在等待同步方法的停止线程,其中可运行对象将字符串列表传递回调用它的接口(interface)。

    @Override
        public synchronized void FilterResults(List<String> Results)  {
            //System.out.println("Result found: " + Results.size());
            try {
            Set<String> hs = new HashSet<>();
            hs.addAll(Results);
            Results.clear();
            Results.addAll(hs);
            for (String tempURL : Results) {
                //System.out.println("Found url: " + tempURL);
                if (!isCompleted(tempURL) && !isQueued(tempURL) && !isRunning(tempURL)) {
                    System.out.println("Added: " + tempURL + " to queue.");
                    queueLink(tempURL);
                    startNewThread(tempURL);
                }
            }
            }catch(Exception e) {

            }
            return;
        }
        private synchronized void startNewThread(String seedURL) {
                if (!isCompleted(seedURL) && !isRunning(seedURL)  ) {
                    if (completedSize("") + runningSize() > 99) {
                        Stop();
                    }

                    String tempProxy = "";
                    String tempPort = "";
                    if (UseProxies) {
                    String Proxy = grabFreeProxy();
                    String[] splitProxy = Proxy.split(":");
                    tempProxy = splitProxy[0]; // 004
                    tempPort = splitProxy[1]; // 034556
                    }
                    //System.out.println("Proxy: " + tempProxy);
                    //System.out.println("Port: " + tempPort);
                    execService.submit(new Crawl(seedURL, this, tempProxy, tempPort, UseProxies));
                    removeFromQueue(url);
                }

            }

@Override
    public Collection<String> Stop() {
        try {
            execService.shutdown();
            if (execService.awaitTermination(45, TimeUnit.SECONDS)) {
                  System.out.println("task completed");
                } else {

                  execService.shutdownNow();

                }
        } catch (InterruptedException e) {

        }
        return PROFILES;
    }

    The Runnable

    public class Crawl implements Runnable{
    public void run() {
            while(!Thread.currentThread().isInterrupted() && shutdown == false) {
             try {
                     //System.out.println(crawler.queueSize());
                     Thread.sleep(100);
                         Crawl(url);
             }catch (InterruptedException e) {
                    Thread.currentThread().interrupt();  // set interrupt flag
                }
       }

      public void crawl(){
         try {
                submitResults(urls); //Calls FilterResults()
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Thread.currentThread().interrupt();
            }
             crawler.removeUsedProxy(Proxy + ":" + Port);
             this.shutdown();
     }
    }

当我调用关闭方法时,需要 45 秒以上,是否有办法可靠地取消任务而无需长时间等待?随着线程数量的增加,这个数字也会增加,并且由于所有线程都在阻塞等待提交结果,因此可能需要一些时间。如果我手动取消任务,我不在乎结果是否已存储,我只需要能够取消即可。有什么想法吗?

Update I've tried ExecutorService#shutdownNow. It has not been reliable when it comes to killing the tasks that are still blocked on the synchronized method.

最佳答案

看起来您需要使用 ExecutorService#shutdownNow如果您不想等待并完成所有工作,您将收到一个包含未执行任务的列表。您可以使用ExecutionService#awaitTermination (参数不超过 45 秒)如果您想要/需要提供等待任务完成的时间。

关于java - Executors.newFixedThreadPool 如何停止同步方法上的所有 Activity 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51271805/

相关文章:

java - 星期几算法错误?

java - 如何像在 xml 中那样改变 java 中 textview 的位置

java - Java 锁是 C 中的 PThread_Mutex 吗?

Java 线程,join() 花费太长时间?

使用 ExitThread 关闭线程 - C

java - 当 ThreadPoolExecutor 的所有任务都完成执行那里的作业时插入数据库

java - 自己的国际化支持就在眼前

java - 单例对象是否有资格进行垃圾回收?类中的静态字段如何进行垃圾收集?

java - 如何从 future 对象中查看执行了哪个线程(名称)

java - 在 Java 中 : how can i terminate execution of all threads without waiting for them to finish their jobs using ExecutorService?