for循环使用多线程优化

package com.xrq;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String args[]) throws InterruptedException {
        Test test = new Test();
        long bt = System.currentTimeMillis();
        List list = new ArrayList<>();
        for(int i=0;i<10;i++){
            list.add(i);
        }
        test.m1(list);
        long et2 = System.currentTimeMillis();
        System.out.println("[1]耗时:"+(et2 - bt)+ "ms");
        Thread thread = new Thread();
        long at = System.currentTimeMillis();
        test.m2();
        long et3 = System.currentTimeMillis();
        System.out.println("[2]耗时:"+(et3 - at)+ "ms");

    }

    public void m1( List list) {
        ExecutorService pool = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(list.size());
        for (int i = 0; i < list.size(); i++) {
            final int index = i;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        new Thread().sleep(1000);
                        //模拟耗时操作
                        System.out.println("[1]" + Thread.currentThread().getName()+"----"+index);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        latch.countDown();
                    }
                }
            };
            pool.execute(run);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("[1] done!");
        pool.shutdown();
    }

    public void m2() {
        for (int i = 0; i < 10; i++) {
            try {
                new Thread().sleep(1000);  //模拟耗时操作
                System.out.println("[2]" + Thread.currentThread().getName()+"----"+i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("[2] done!");
    }
}

 

你可能感兴趣的:(for循环使用多线程优化)