随手 - 并发coding

    private static int sum(int a) throws Exception {
        Thread.sleep(1000);
        return 100 + a;
    }

    public static void main(String[] args) throws Exception {
        long now = System.currentTimeMillis();
        ExecutorService service = Executors.newFixedThreadPool(10);
        List> futureList = Lists.newArrayList();
        for (int i = 1; i <= 10; i++) {
            final int a = i;
            Future future = service.submit(new Callable() {
                @Override
                public Integer call() throws Exception {
                    return sum(a);
                }
            });
            futureList.add(future);
        }
        service.shutdown();
        for (Future future : futureList) {
            System.out.println(future.get());
        }
        System.out.println((System.currentTimeMillis() - now) / 1000);

        now = System.currentTimeMillis();
        List list = Lists.newArrayList();
        for (int i = 1; i <= 10; i++) {
            list.add(sum(i));
        }
        for (int i : list) {
            System.out.println(i);
        }
        System.out.println((System.currentTimeMillis() - now) / 1000);
    }

 

你可能感兴趣的:(Java)