工作中如何使用线程池的?自己如何定义一个线程池?
生活随笔
收集整理的這篇文章主要介紹了
工作中如何使用线程池的?自己如何定义一个线程池?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工作中如何使用線程池的?自己如何定義一個線程池?
import java.util.concurrent.*;public class MyThreadPoolDemo {public static void main(String[] args) {ExecutorService threadPool = new ThreadPoolExecutor(2,5,1L,TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>(3),Executors.defaultThreadFactory(),//默認拋出異常 // new ThreadPoolExecutor.AbortPolicy()//回退調用者new ThreadPoolExecutor.CallerRunsPolicy()//處理不來的不處理//new ThreadPoolExecutor.DiscardOldestPolicy() // new ThreadPoolExecutor.DiscardPolicy());//模擬10個用戶來辦理業務 沒有用戶就是來自外部的請求線程.try {for (int i = 1; i <= 10; i++) {threadPool.execute(() -> {System.out.println(Thread.currentThread().getName() + "\t 辦理業務");});}} catch (Exception e) {e.printStackTrace();} finally {threadPool.shutdown();}//threadPoolInit();}private static void threadPoolInit() {/*** 一池5個處理線程*///ExecutorService threadPool= Executors.newFixedThreadPool(5);/*** 一池一線程*///ExecutorService threadPool= Executors.newSingleThreadExecutor();/*** 一池N線程*/ExecutorService threadPool = Executors.newCachedThreadPool();//模擬10個用戶來辦理業務 沒有用戶就是來自外部的請求線程.try {for (int i = 1; i <= 20; i++) {threadPool.execute(() -> {System.out.println(Thread.currentThread().getName() + "\t 辦理業務");});try {TimeUnit.MICROSECONDS.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();} finally {threadPool.shutdown();}} }
?
總結
以上是生活随笔為你收集整理的工作中如何使用线程池的?自己如何定义一个线程池?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生产上如何设置线程池参数?拒绝策略怎么配
- 下一篇: 线程池配置合理线程数?