所谓线程池就是多个线程封装在一起操作,线程池对任务进行操作的时候,有几种运行操作型式,单线程,无限多,限定长度,对线程池操作的核心就类和方法定义在java.util.concurrent包中,其中有两个比较核心 的接口:
1.普通的执行线程池定义:Interface ExecutorService
2.调度线程池:java.util.concurrent.ScheduledExecutorService
创建一个线程池可以使用java.util.concurrent.Executors类
。创建无大小的线程池:public static ExecutorService newCachedThreadPool()
。创建固定大小的线程池:public static ExecutorService newFixedThreadPool(int nThreads)
。单线程池:public static ScheduledExecutorService newSingleThreadScheduledExecutor()
。穿件定时调度池:public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
几种的实现demo
package com.wjx.sayHello;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestDemo {
public static void main(String[] args) throws InterruptedException{
/*
* ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
for(int x=0;x<10;x++){
//Thread.sleep(200);
int temp=x;
newCachedThreadPool.submit(()->{
System.out.println(Thread.currentThread().getName()+"==="+temp);
});
}
newCachedThreadPool.shutdown();*/
// ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor();
// for(int x=0;x<10;x++){
// //Thread.sleep(200);
// int temp=x;
// newCachedThreadPool.submit(()->{
// System.out.println(Thread.currentThread().getName()+"==="+temp);
// });
// }
//
// newCachedThreadPool.shutdown();
// ExecutorService newCachedThreadPool = Executors.newFixedThreadPool(4);
// for(int x=0;x<10;x++){
// //Thread.sleep(200);
// int temp=x;
// newCachedThreadPool.submit(()->{
// System.out.println(Thread.currentThread().getName()+"==="+temp);
// });
// }
//
// newCachedThreadPool.shutdown();
ScheduledExecutorService newCachedThreadPool = Executors.newScheduledThreadPool(1);
for(int x=0;x<10;x++){
//Thread.sleep(200);
int temp=x;
newCachedThreadPool.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==="+temp);
System.out.println("****************************************");
}
}, 3, 2, TimeUnit.SECONDS);
}
}
}