Java 线程池 四种创建方式

Java通过Executors提供四种线程池,分别为:

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。


newCachedThreadPool


  
  
  1. public static void main(String[] args) {
  2. ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
  3. for (int i = 0; i < 10; i++) {
  4. final int index = i;
  5. try {
  6. Thread.sleep(10);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. cachedThreadPool.execute(new Runnable() {
  11. public void run() {
  12. System.out.println(index);
  13. }
  14. });
  15. }
  16. }
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

这里的线程池是无限大的,当一个线程完成任务之后,这个线程可以接下来完成将要分配的任务,而不是创建一个新的线程,

java api 1.7 will reuse previously constructed threads when they are available.


newFixedThreadPool 


  
  
  1. public static void main(String[] args) {
  2. ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
  3. for (int i = 0; i < 10; i++) {
  4. final int index = i;
  5. fixedThreadPool.execute(new Runnable() {
  6. public void run() {
  7. try {
  8. System.out.println(index);
  9. Thread.sleep(10);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. });
  15. }
  16. }


创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()


  
  
  1. public static void main(String[] args) {
  2. ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
  3. for (int i = 0; i < 10; i++) {
  4. scheduledThreadPool.schedule(new Runnable() {
  5. public void run() {
  6. System.out.println("delay 3 seconds");
  7. }
  8. }, 3, TimeUnit.SECONDS);
  9. }
  10. }



newSingleThreadExecutor 


  
  
  1. public static void main(String[] args) {
  2. ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
  3. for (int i = 0; i < 10; i++) {
  4. final int index = i;
  5. singleThreadExecutor.execute(new Runnable() {
  6. public void run() {
  7. /* System.out.println(index);*/
  8. try {
  9. System.out.println(index);
  10. Thread.sleep(2000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. });
  16. }
  17. }

按顺序来执行线程任务   但是不同于单线程,这个线程池只是只能存在一个线程,这个线程死后另外一个线程会补上


猜你喜欢

转载自blog.csdn.net/qq_22771739/article/details/82811119