当前位置: 代码迷 >> J2SE >> JAVA 的concurrent 用法,怎么让启动的线程都执行完毕后 再统一输出结果
  详细解决方案

JAVA 的concurrent 用法,怎么让启动的线程都执行完毕后 再统一输出结果

热度:16   发布时间:2016-04-23 20:34:12.0
JAVA 的concurrent 用法,如何让启动的线程都执行完毕后 再统一输出结果
本帖最后由 lgmsyy 于 2014-07-07 13:52:06 编辑
情景:
  假设每次执行都要开启N个线程,每个线程将结果保存到Map中,当N个线程都结束的时候,Map中就保存N结果。
我想咨询的是,我如何控制 将所有线程结束后,才将Map中的结果都取出来。
public class TestSemaphore {
                public static void main(String[] args) {
                // 线程池
                ExecutorService exec = Executors.newCachedThreadPool();

                // 只能2个线程同时访问
                final Semaphore semp = new Semaphore(2);

                 // 模拟20个客户端访问
                 for (int index = 0; index < 10; index++) {
                              final int NO = index;
                              Runnable run = new Runnable() {
                                                 public void run() {
                                                            try {                                                                   
                                                                    semp.acquire(2);
                                                                    System.out.println("Accessing: " + NO);
                                                                    Thread.sleep((long) (Math.random() * 10000));
                                                                   
                                                                    semp.release(2);
                                                                    System.out.println("-----------------"+semp.availablePermits());
                                                            } catch (InterruptedException e) {
                                                                    e.printStackTrace();
  相关解决方案