java 多线程,Java并发编程:线程池的使用

1:

ExecutorService executor = new ThreadPoolExecutor(5, 5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
list.forEach(a -> {
    executor.submit(() -> {
        //    业务操作
    });

});
executor.shutdown();

try {
    boolean loop = true;
    do {
        loop = !executor.awaitTermination(2, TimeUnit.SECONDS);
    } while (loop);
} catch (InterruptedException e) {
    Loggers.BIZ.error("error", e);
}

2:

// 产生一个 ExecutorService 对象,这个对象带有一个大小为 poolSize 的线程池,若任务数量大于 poolSize ,任务会被放在一个 queue 里顺序执行。
ExecutorService executor = Executors.newFixedThreadPool(5);

for (Integer num = 0; num < 999; num++) {
    Runnable runner = new ThreadTest(num);
    executor.execute(runner);
}

executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
ThreadTest

/**
 * 多线程扩展方法
 * */
public class ThreadTest implements Runnable {
    /**
     * table对象
     */
    private Integer num;

    public RecognitionTableThread(Integer num) {
        this.num = num;
    }

    @Override
    public void run() {
        //    操作
    }
}

 

多线程原理和实现参考:Java并发编程:线程池的使用

 

    原文作者:Fish-Blog
    原文地址: https://www.cnblogs.com/Cailf/p/10333112.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞