线程池.........池池池..........
程序员文章站
2022-05-06 07:52:40
...
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
//创建可缓存线程池,如果不够的话,灵活回收空闲线程,若无可回收,新建线程
//线程池无限大,如果执行第二个任务时第一个任务已经完成,则复用执行第一个任务的线程
//ExecutorService executorService= Executors.newCachedThreadPool();
//创建一个定长的线程池,可控制线程最大并发数,超出的线程会在队列中等待
//ExecutorService executorService=Executors.newFixedThreadPool(3);
//创建一个定长线程池,支持定长及周期性任务执行
//ScheduledExecutorService executorService=Executors.newScheduledThreadPool(5);
//定时任务
//executorService.schedule(....);
//周期性任务执行
/*executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("延迟三秒执行");
}
},1,3,TimeUnit.SECONDS);*/
ExecutorService executorService=Executors.newSingleThreadExecutor();
for(int i=0;i<5;i++){
executorService.execute(new MyTask(i));
}
/* for(int i=0;i<10;i++){
executorService.execute(new MyTask(i));
}*/
}
}