天天看点

ExecutorService java线程池主线程等待子线程执行完成

java1.5及1.6中通过ExecutorService提供了线程池的支持。我们可以按照如下的方法建立10个线程容量的线程池:

ExecutorService exec = Executors.newFixedThreadPool(10);
            for (i = 0; i < taskAmount; i++)
                          exec.execute(new Task(...)); // 或者new Thread(...)
           

这样就把所有的任务提交给了线程池,由exec负责调度线程的执行,切换。

我们还应该加上下面一行代码:

exec.shutdown();
           

这样线程池在任务结束之后才会终止。我的问题是这样的:线程池的使用只是主线程的一个中间过程,而我必须等线程池中止之后才能继续后续的操作。所以我在上面的代码后面加上线程池中止判断语句,如果线程池仍在工作,主线程sleep。

while (!exec.isTerminated())
            {
                  try
                  {
                         Thread.sleep(1000);
                  } catch (InterruptedException e)
                  {
                         e.printStackTrace();
                  }
            }
           

可是我总觉得这不是最好的中止判断方式,至于哪里不好么……我也不清楚,只是觉得java应该提供更友好的接口,比如说可以让主线程等待线程池结束的方法,但是我没有找到。因此请教一下各路同道,有没有一种更好的方式实现呢? 先行谢过哦……

ExecutorService java线程池主线程等待子线程执行完成

==============================

public class MassTestClient {

    /

    private static int threadPoolSize = 10; // TODO configurable

    private static String testCasesFile = "./service/client/config/pc/testCases.dat";

    private static DateFormat dformat = new SimpleDateFormat("MM/dd/yyyy");

    public static void main(String args[]) {

        try {

             ....

            ExecutorService exec = Executors.newFixedThreadPool(threadPoolSize, testClient.new TestClientThreadFactory());

            List<String[]> list = readByBufferReader(testCasesFile);

            for (String[] str : list) {

                exec.execute(testClient.new testClientThread(tmlModule, str));

            }

            exec.shutdown() ;//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

            while (!exec.isTerminated()) { //Returns true if all tasks have completed following shut down.

                         // Note that isTerminated is never true unless either shutdown or shutdownNow was called first.

                try {

                    Thread.sleep(1000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

            System.out.println("Execution complete");

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            System.exit(0);

        }

    }

    private class testClientThread implements Runnable {

        private String code;

        private String id;

        private String country;

        private Date date;

        private OPSTechModule module;

        public testClientThread(OPSTechModule module, String[] str) throws Exception {

            this.code = str[0];

            this.id = str[1];

            this.country = str[2];

            this.date = dformat.parse(str[3]);

            this.module = module;

        }

        @Override

        public void run() {

            System.out.println(Thread.currentThread().getName() + "  " + code + "|" + id + "|" + country + "|" + date);

            ISGSecurityDocument result = module.tmlSearch(code, id, country, date);

            if (result != null)

                System.out.println(result.toString());

        }

    }

    private class TestClientThreadFactory implements ThreadFactory {

        int counter = 0;

        @Override

        public Thread newThread(Runnable runnable) {

            Thread thr = new Thread(runnable);

            ++counter;

            thr.setName("testClient-" + counter);

            return thr;

        }

    }

    public static List<String[]> readByBufferReader(String file) {

        List<String[]> list = new ArrayList<String[]>();

        try {

            BufferedReader br = new BufferedReader(new FileReader(new File(file)));

            String line;

            while ((line = br.readLine()) != null && !line.trim().isEmpty()) {

                // System.out.println(line);

                String str[] = line.trim().split("\\|");

                list.add(str);

            }

            br.close();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        return list;

    }

}