Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
(1)可缓存线程池 CachedThreadPool
ExecuterService exec = Executers.newCachedThreadPool(new CustomThreadFactory());
(2)定长线程池 用的最多的线程池 FixedThreadPool
ExecuterService exec = Executers.newFixedThreadPool(3,new CustomThreadFactory()); //thread Num
(3)可调度线程池 ScheduledTreadPool
ScheduledExecuterService exec = Executers.newScheduledThreadPool(3,new CustomFactory());
(4)单线程化线程池 SingleThreadExecutor
ExecuterService exec = Executer.newSingleThreadExecutor(new CustomFactory());
测试类如下:
CustomTask.class:
public class CustomTask implements Runnable{
private int id= 0;
public CustomTask(intid){
this.id= id;
}
@Override
publicvoidrun() {
//TODOAuto-generated method stub
System.out.println("时间:"+System.currentTimeMillis()+" id="+id);
try{
Thread.sleep(1000);
}catch(InterruptedException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
}
}
CustomThreadFactory.class
public class CustomThreadFactory implementsThreadFactory{
@Override
publicThread newThread(Runnable r) {
//TODOAuto-generated method stub
Thread t =newThread(r);
returnt;
}
}
TestMain.class
publicclassTesThread {
/**
*@paramargs
*/
publicstaticvoidmain(String[] args) {
//TODOAuto-generated method stub
//定长线程池
// testFixedThreadPool();
// testCahedThreadPool();
// testScheduledThreadPoolDelead();
// testSchedulRate();
// testSingleThreadPool();
}
/**
* 可缓存线程池,
*/
publicstaticvoidtestCahedThreadPool(){
ExecutorService exec = Executors.newCachedThreadPool(newCustomThreadFactory());
for(inti=0;i<10;i++){
exec.submit(newCustomTask(i));
}
exec.shutdown();
}
/**
* 定长线程池,超过数目,将排对等待
*
*/
public static void testFixedThreadPool(){
ExecutorService exec = Executors.newFixedThreadPool(1,newCustomThreadFactory());
for(inti=0;i<5;i++){
exec.submit(newCustomTask(i));
}
exec.shutdown();
}
/**
* 调度线程池之延迟执行线程池
*/
public static void testScheduledThreadPoolDelead(){
ScheduledExecutorService exec = Executors.newScheduledThreadPool(3,newCustomThreadFactory());
for(inti=0;i<5;i++){
exec.schedule(newCustomTask(i), 3,TimeUnit.SECONDS);
}
// exec.shutdown();
}
/**
* 循环调度线程
*/
public static void testSchedulRate(){
Scheduled ExecutorService exec = Executors.newScheduledThreadPool(3,newCustomThreadFactory());
for(inti=0;i<5;i++){
exec.scheduleAtFixedRate(newCustomTask(i), 1, 5, TimeUnit.SECONDS);
}
exec.shutdown();
}
/**
* 单线程,线程池
*/
public static void testSingleThreadPool(){
ExecutorService exec = Executors.newSingleThreadExecutor(newCustomThreadFactory());
for(inti=0;i<5;i++){
exec.submit(newCustomTask(i));
}
exec.shutdown();
}
}