JAVA多线程处理for循环

public static void main(String[] args) {
    
    
        long start = System.currentTimeMillis();
        List<Integer> list = new ArrayList();
        for (int i = 0; i < 1000; i++) {
    
    
            list.add(i);
        }
        //定义线程数量为20,可根据服务器配置适当调整大小        
        Thread(list, 20);
        long end = System.currentTimeMillis();
        System.out.println("总时间 = " + (end - start));
    }
//此处有加锁,不需要的同学可以自行改造
public synchronized static <T> void Thread(List<T> list, int nThread) {
    
    
        if (CollectionUtils.isEmpty(list) || nThread <= 0 || CollectionUtils.isEmpty(list)) {
    
    
            return;
        }
        Semaphore semaphore = new Semaphore(nThread);//定义几个许可
        ExecutorService executorService = Executors.newFixedThreadPool(nThread);//创建一个固定的线程池
        for (T number : list) {
    
    
            try {
    
    
                semaphore.acquire();
                executorService.execute(() -> {
    
    
                //此处可以放入待处理的业务
                System.out.println("number:" + number);
                semaphore.release();
                });
            } catch (InterruptedException e) {
    
    

            }
        }
        executorService.shutdown();
    }

在数据量大的情况下对比直接循环效果很明显。用上之后又可以加鸡腿了~

猜你喜欢

转载自blog.csdn.net/JST888_K/article/details/111865941
今日推荐