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并发编程:线程池的使用