Java ExecutorService四种线程池的例子与说明

转载:

1、new Thread的弊端

执行一个异步任务你还只是如下new Thread吗?

new Thread(new Runnable() {  

    @Override  
    public void run() {  
        // TODO Auto-generated method stub  
    }  
}).start();  

弊端:
a、每次new Thread新建对象性能差
b、线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统导致死机
c、缺乏更多功能,如定时执行,定期执行,线程中断;

2、Java线程池

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

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  
for (int i = 0; i < 10; i++) {  
    final int index = i;  
    try {  
        Thread.sleep(index * 1000);  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    }  

    cachedThreadPool.execute(new Runnable() {  

        @Override  
        public void run() {  
            System.out.println(index);  
        }  
    });  
} 
2)newFixedThreadPool:创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

   ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  
for (int i = 0; i < 10; i++) {  
    final int index = i;  
    fixedThreadPool.execute(new Runnable() {  


        @Override  
        public void run() {  
            try {  
                System.out.println(index);  
                Thread.sleep(2000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    });  
} 

3)newScheduledThreadPool:创建一个定长线程池,制定定时及周期性任务执行,延迟执行实例代码如下:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
scheduledThreadPool.schedule(new Runnable() {  

    @Override  
    public void run() {  
        System.out.println("delay 3 seconds");  
    }  
}, 3, TimeUnit.SECONDS);  //表示延迟3秒执行

定期执行实例代码如下:

scheduledThreadPool.scheduleAtFixedRate(new Runnable() {  

    @Override  
    public void run() {  
        System.out.println("delay 1 seconds, and excute every 3 seconds");  
    }  
}, 1, 3, TimeUnit.SECONDS); //表示延迟1秒后每3秒执行一次。

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

  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
for (int i = 0; i < 10; i++) {  
    final int index = i;  
    singleThreadExecutor.execute(new Runnable() {  

        @Override  
        public void run() {  
            try {  
                System.out.println(index);  
                Thread.sleep(2000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    });  
}   
;