1.底层类:ThreadpoolExecutor类
创建线程池对象:ThreadpoolExecutor t= new ThreadpoolExecutor(核心线程数,最大线程数,时间,时间单位,阻塞队列)
创建线程池:
package threadpool;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
class thread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Threadpool01 {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(1, 2, 3, TimeUnit.SECONDS,new LinkedBlockingQueue<>(4));
threadPoolExecutor.execute(new thread());//1,由核心线程去执行
threadPoolExecutor.execute(new thread());//2 队列排队
threadPoolExecutor.execute(new thread());//3 队列排队
threadPoolExecutor.execute(new thread());//4 队列排队
threadPoolExecutor.execute(new thread());//5 队列排队
threadPoolExecutor.execute(new thread());//6
// threadPoolExecutor.execute(new thread());//超过线程池最大容量 报错
threadPoolExecutor.shutdown();//关闭线程池
}
}
一个线程池能容纳的最大线程个数为:最大线程总量加队列个数
--------------------------
线程池分类:
1.可缓存:
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//可缓存的线程池
public class Threadpool {
public static void main(String[] args) {
ExecutorService executorService= Executors.newCachedThreadPool();
for (int i=0;i<15;i++){
executorService.execute(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
executorService.shutdown();
}
}
2.定长类:
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Threadpool02 {
public static void main(String[] args) {
ExecutorService executorService= Executors.newFixedThreadPool(3);//3代表核心线程数,也代表最大线程数
for (int i=0;i<150;i++){
executorService.execute(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
executorService.shutdown();
}
}
3.定时线程池:
package threadpool;
import java.sql.Time;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Threadpool03 {
public static void main(String[] args) {
ScheduledExecutorService ses= Executors.newScheduledThreadPool(3);//3代表核心线程数,也代表最大线程数
for (int i=0;i<150;i++){
ses.schedule(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
},3, TimeUnit.SECONDS);//3秒后执行任务
}
ses.shutdown();
}
}
4.单例线程池
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Threadpool04 {
public static void main(String[] args) {
ExecutorService executorService= Executors.newSingleThreadExecutor();
for (int i=0;i<150;i++){
executorService.execute(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
executorService.shutdown();
}
}