Threadpool Executor完成时如何给出消息?

How to give message when Threadpool Executor is completed?

我正在尝试在我的 ThreadpoolExecutor 执行完毕时弹出警告消息。它正在从网站搜索电子邮件地址,完成后我想要一条警告消息 "Completed"。这是我的主题:-

public class Constant
    {
      public  static final int NUM_OF_THREAD = 60;
      public  static final int TIME_OUT = 10000;
    }
    ThreadPoolExecutor poolMainExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool
            (Constant.NUM_OF_THREAD);

这是我的搜索操作class :-

class SearchingOperation implements Runnable {

        URL urldata;
        int i;
        Set<String> emailAddresses;
        int level;

        SearchingOperation(URL urldata, int i, Set<String> emailAddresses, int level) {
            this.urldata = urldata;
            this.i = i;
            this.emailAddresses = emailAddresses;
            this.level = level;
            if (level != 1)
                model.setValueAt(urldata.getProtocol() + "://" + urldata.getHost() + "/contacts", i, 3);

        }

        public void run() {
            BufferedReader bufferreader1 = null;
            InputStreamReader emailReader = null;
            System.out.println(this.i + ":" + poolMainExecutor.getActiveCount() + ":" + level + ";" + urldata.toString());

            try {
                if (level < 1) {
                    String httpPatternString = "https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)";
                    String httpString = "";
                    BufferedReader bufferreaderHTTP = null;
                    InputStreamReader httpReader = null;
                    try {

                        httpReader = new InputStreamReader(urldata.openStream());
                        bufferreaderHTTP = new BufferedReader(httpReader
                        );
                        StringBuilder rawhttp = new StringBuilder();
                        while ((httpString = bufferreaderHTTP.readLine()) != null) {

                            rawhttp.append(httpString);

                        }
                        if (rawhttp.toString().isEmpty()) {
                            return;
                        }
                        List<String> urls = getURL(rawhttp.toString());
                        for (String url : urls) {
                            String fullUrl = getMatchRegex(url, httpPatternString);
                            if (fullUrl.isEmpty()) {
                                if (!url.startsWith("/")) {
                                    url = "/" + url;
                                }

                                String address = urldata.getProtocol() + "://" + urldata.getHost() + url;
                                fullUrl = getMatchRegex(address, httpPatternString);

                            }
                            if (!addressWorked.contains(fullUrl) && fullUrl.contains(urldata.getHost())) {
                                addressWorked.add(fullUrl);
                                sendToSearch(fullUrl);

                            }
                        }


                    } catch (Exception e) {
                        //System.out.println("652" + e.getMessage());
                        //e.printStackTrace();
                        return;
                    } finally {
                        try {
                            if (httpReader != null)
                                bufferreaderHTTP.close();
                        } catch (Exception e) {
                            // e.printStackTrace();
                        }
                        try {
                            if (httpReader != null)
                                httpReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                }
                String someString = "";
                emailReader = new InputStreamReader(urldata.openStream());
                bufferreader1 = new BufferedReader(
                        emailReader);
                StringBuilder emailRaw = new StringBuilder();
                while ((someString = bufferreader1.readLine()) != null) {
                    if (someString.contains("@")) {
                        emailRaw.append(someString).append(";");
                    }
                }
                //Set<String> emailAddresses = new HashSet<String>();
                String emailAddress;
                //Pattern pattern = Pattern
                //.compile("\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b");
                Pattern
                        pattern = Pattern
                        .compile("\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b");

                Matcher matchs = pattern.matcher(emailRaw);
                while (matchs.find()) {
                    emailAddress = (emailRaw.substring(matchs.start(),
                            matchs.end()));
                    //  //System.out.println(emailAddress);
                    if (!emailAddresses.contains(emailAddress)) {
                        emailAddresses.add(emailAddress);
                        //  //System.out.println(emailAddress);
                        if (!foundItem.get(i)) {
                            table.setValueAt("Found", i, 4);
                            foundItem.set(i, true);
                        }

                        String emails = !emailAddresses.isEmpty() ? emailAddresses.toString() : "";
                        model.setValueAt(emails, i, 2);
                        model.setValueAt("", i, 3);
                    }
                }
            } catch (Exception e) {
                //System.out.println("687" + e.getMessage());
            } finally {
                try {
                    if (bufferreader1 != null)
                        bufferreader1.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    if (emailReader != null)
                        emailReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Thread.currentThread().interrupt();
                return;
            }
        }

在此之后是最后的片段:-

 private void sendToSearch(String address) throws Throwable {
            SearchingOperation operation = new SearchingOperation(new URL(address), i,
                    emailAddresses, level + 1);
            //operation.run();
            try {
                final Future handler = poolMainExecutor.submit(operation);

                try {
                    handler.get(Constant.TIME_OUT, TimeUnit.MILLISECONDS);
                } catch (TimeoutException e) {
                    e.printStackTrace();
                    handler.cancel(false);
                }
            } catch (Exception e) {
                //System.out.println("Time out for:" + address);
            } catch (Error error) {
                //System.out.println("Time out for:" + address);

            } finally {
            }
        }

这段代码可以使用。它会每2.5秒检查一次执行是否完成。

do {
        System.out.println("In Progress");
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (poolMainExecutor.getActiveCount() != 0);

    System.out.println("Completed");

实施 Callable<Void> 而不是 Runnable 并等待所有任务通过调用 Future<Void>.get():

终止
class SearchingOperation implements Callable<Void>
{
   public Void call() throws Exception
   {
      //same code as in run()
   }
}

//submit and wait until the task complete
Future<Void> future = poolMainExecutor.submit(new SearchingOperation()).get();

使用ThreadPoolExecutor.awaitTermination():

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

在您的代码中,您先创建 ThreadPoolExecutor

ThreadPoolExecutor poolMainExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Constant.NUM_OF_THREAD);

然后,您需要为其添加任务:

poolMainExecutor.execute(myTask);
poolMainExecutor.submit(myTask);

execute 将 return 什么都没有,而 submit 将 return 一个 Future object。任务必须实现 RunnableCallable。例如,SearchingOperation 的 object 是一项任务。线程池将并行执行任务,但每个任务将由一个线程执行。这意味着要有效地使用 NUM_OF_THREAD 个线程,您至少需要添加 NUM_OF_THREAD 个任务。

(可选)让所有作业正常工作后,关闭池。这将阻止提交新任务。它不会影响 运行 个任务。

poolMainExecutor.shutdown();

最后,您需要等待所有任务完成。最简单的方法是调用

poolMainExecutor.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);

您应该调整在抛出异常之前等待任务完成的时间。

既然工作已经完成,请通知用户。一种简单的方法是从 JOptionPane 调用其中一个对话框预设,例如:

JOptionPane.showMessageDialog(null, "message", "title", JOptionPane.INFORMATION_MESSAGE);

它会弹出一个 window 标题 "title"、消息 "message"、一个 "information" 图标和一个关闭它的按钮。