package Juc;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* java多线程的方式4种
* 1.继承Thread类
* 2.实现runable接口
* 3.实现collable接口
* 4.从线程池获取
* System.out.println(Runtime.getRuntime().availableProcessors());//电脑核数
* 线程池运行原理+7大参数:
*
*
*/
public class MyThreadPool {
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(
2,
5,//cpu密集型没有阻塞max=(cpu核数+1)计算减少cpu上下文切换,Io密集型max=(cpu核数*2)访问数据库,cpu核数=x*(0.8-0.9)
1L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3), //有界阻塞队列
Executors.defaultThreadFactory(),//线程池工厂
new ThreadPoolExecutor.DiscardPolicy());//拒绝策略:4种->
//AbortPolicy();超过max+阻塞队列抛出异常
//CallerRunsPolicy();超出max+阻塞队列把请求退回给调用者
//DiscardOldestPolicy();超出max+阻塞队列把请求任务种最久的抛弃
//DiscardPolicy();超出max+阻塞队列把超出的请求丢弃
try {
//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
for (int i = 1; i <=8; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t"+"办理业务");
});
//暂停一会儿线程
}
} finally {
threadPool.shutdown();
}
}
/**
* JDK集成,一般不用原因:有界队列
* )FixedThreadPool 和 SingleThreadPool:
* 允许的请求队列长度为 Integer.MAX_VALUE,
* 可能会堆积大量的请求,从而导致 OOM。
* 2)CachedThreadPool 和 ScheduledThreadPool:
* 允许的创建线程数量为 Integer.MAX_VALUE,
* 可能会创建大量的线程,从而导致 OOM。
*/
public static void threadPoolInit() {
//ExecutorService threadPool = Executors.newFixedThreadPool(5);
ExecutorService threadPool = Executors.newSingleThreadExecutor(); //7种常用的3次
//ExecutorService threadPool = Executors.newCachedThreadPool();
try {
//模拟10个用户来办理业务,每个用户就是一个来自外部的请求线程
for (int i = 1; i <=10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t"+"办理业务");
});
//暂停一会儿线程
//try{TimeUnit.MILLISECONDS.sleep(200);}catch (Exception e){e.printStackTrace();}
}
} finally {
threadPool.shutdown();
}
}
}
手写线程池
最新推荐文章于 2024-05-29 07:55:49 发布