ExecutorService停止并等待另一个ExecutorService以Java完成

时间:2016-03-05 14:46:29

标签: java multithreading threadpool

我有两个ExecutorService个实例:一个有4个线程,另一个有20个线程。我希望按下按钮,服务1停止并等待服务2结束。然后,服务1继续运行。

我尝试使用waitnotify执行此操作但是它没有按预期工作:

ExecutorService 1:

    public void readFile(JTextArea textArea) {
    try {
        File file = new File(this.fm.fullPath);
        if (!file.exists()) {
            return;
        }
        BufferedReader br = new BufferedReader(new FileReader(this.fm.fullPath));

        ExecutorService executor = Executors.newFixedThreadPool(main.TOTALSTRINGS);

        String line = br.readLine();

        int i=1;
        while (line != null) {
            powThread t = new powThread("Thread" + (i+1), line, textArea);
            executor.execute(t);
            line = br.readLine();
            i++;
        }

        executor.shutdown();
        Thread t = new Thread() {
            public void run() {
                try {
                    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                    br.close();
                } catch (Exception e) {

                }
            }
        };
        t.start();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

ExecutorService2:

    public void generateNumStrings(JTextArea textArea) {
    StringGenerator sg = new StringGenerator();

    int[] dynamicThreads = main.calcThreadsTotal();
    int totalThreads = dynamicThreads.length;

    ExecutorService executor = Executors.newFixedThreadPool(totalThreads);

    for(int i=0; i<totalThreads; i++) {
        generateThread t = new generateThread("Thread" + (i+1), sg, dynamicThreads[i], this.fm);
        executor.execute(t);
    }

    executor.shutdown();

    Thread t = new Thread() {
        public void run() {
            try {
                textArea.setText("");
                executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
                textArea.append("File write successfully!");
            } catch (InterruptedException e) {

            }
        }
    };
    t.start();
}

1 个答案:

答案 0 :(得分:2)

您可以在第一个ExecutorService中使用AtomicReference来包装第二个ExecutorService,如果第二个ExecutorService没有被实例化,则可以使用null,然后{{ 1}}如果引用为非null。我假设awaitTerminationreadFile属于同一个班级,如果没有,那么您需要找到一些方法让generateNumStrings对{{1}可见}}

AtomicReference