线程池在juc包下。
创建线程4种方式:继承Thread、实现Runnable、Callable、创建线程池
一:线程池优点
1.降低资源消耗:通过重复利用已创建的线程,降低线程创建与销毁带来的损耗,手动创建线程:假如线程执行结束,就会销毁线程,损耗大;
2.提高响应速度:当新任务到达时,任务不需要等待创建就可以立即执行;(线程池有空闲线程,只要有任务,就会利用这些空闲线程)
3.提高线程的可管理性:使用线程池可以统一进行线程的分配、调度与监控。(手动创建线程不知道当前有多少个线程,创建线程池有大小)。
二:线程池执行任务流程
1.首先判断核心线程池中的线程是否都在执行任务,如果是,再次查看核心线程池是否已满,如果未满,创建新的线程执行任务(即使有空闲线程,只要没满,也会创建新的线程)。如果核心线程池有空闲线程,则将任务直接分配给空闲线程执行。否则执行第二步。
2.判断工作队列(BlockingQueue)是否已满,如果工作队列没有满,将提交任务存储到工作队列等待核心池的调度,否则若工作队列已满,进行第三步。
3.判断当前线程池中的线程数量是否已将达到最大值maxiumSize,若达到最大值,将任务交给饱和策略处理,否则创建新线程执行此任务。
三.线程池的使用
1.手工创建线程池:
通过创建ThreadPoolExecutor来创建线程池
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
参数解释:
- corePoolSize:核心池大小,当提交任务到线程池时,线程池会创建一个新的线程来执行任务,即使核心池有其他空闲线程也会创建新线程,一直到线程数达到核心池的最大大小。
调用prestartAllCoreThreads()线程池会提前创建线程达到核心线程池最大值并启动所有核心线程。 - workQueue(工作队列):用于保存等待执行任务的阻塞队列。
可以选择一下几个阻塞队列:
a. ArrayBlockingQueue:基于数组结构的有界阻塞队列,此队列按照FIFO原则对元素进行排序;
b: LinkedBlockingQueue:基于链表结构的阻塞队列,按照FIFO排序元素,吞吐量高于
ArrayBlockingQueue,Executors.newFixedThreadPool()是固定大小线程池,采用此队列;
c : SynchronousQueue :一个不存储元素的阻塞队列,是无界队列(不限制个数,只要有任务插入会阻塞排队)。
每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量一般比LinkedBlockingQueue要高。Executors.newCachedThreadPool()采用此队列。
d: PriorityBlockingQueue:具有优先级的无界阻塞队列(优先级队列底层是堆)。 - maximumPoolSize(线程池最大线程数量):线程池允许创建的最大线程数。如果队列已满并且已创建的线程数小于此参数,则线程池会再创建新的线程执行任务。否则,调用饱和策略处理。如果采用最大队列,此参数无意义。
- keepAliveTime(线程保持活动时间): 线程池的工作线程空闲后,保持存活的时间。若任务很多,并且每个任务执行的时间较短,可以调大此参数来提高线程利用率。
- TimeUnit(keepAliveTime时间单位)
- RejectedExecutionHandler(饱和策略):当队列和线程池都满,说明线程池处于饱和状态,此时采用饱和策略来处理任务,默认采用AborPolicy。
JDK一共内置4个饱和策略:
a: AbortPolicy ,表示无法处理抛出异常,JDK默认采用此策略;
b: CallerRunsPolicy ,等待调用者线程空闲后运行此任务。比如是主线程调用调用池,当线程池空闲后,主线程会运行此任务。
c: DiscardOldestPolicy ,丢弃阻塞队列中最近的一个任务,并执行当前任务。
d: DiscardPolicy ,不处理,直接将新任务丢弃,也不报错。
四: 创建线程池实例:
参数是Runnable
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class Mthread implements Runnable
{
@Override
public void run() {
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
public class TestExecutor {
public static void main(String[] args) {
Mthread mthread=new Mthread();
ExecutorService executorService=new ThreadPoolExecutor(
3,5,2000,TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>()); //创建线程池
for(int i=0;i<4;i++)
{
executorService.execute(mthread);
//4个线程,但是在这里核心池3个线程可以处理当前4个线程,每个线程都要执行循环10次
}
executorService.shutdown();
}
}
结果如下:
pool-1-thread-1、0
pool-1-thread-3、0
pool-1-thread-2、0
pool-1-thread-3、1
pool-1-thread-1、1
pool-1-thread-3、2
pool-1-thread-2、1
pool-1-thread-3、3
pool-1-thread-1、2
pool-1-thread-3、4
pool-1-thread-2、2
pool-1-thread-3、5
pool-1-thread-1、3
pool-1-thread-3、6
pool-1-thread-2、3
pool-1-thread-3、7
pool-1-thread-1、4
pool-1-thread-3、8
pool-1-thread-2、4
pool-1-thread-3、9
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-2、5
pool-1-thread-1、7
pool-1-thread-3、0
pool-1-thread-1、8
pool-1-thread-2、6
pool-1-thread-1、9
pool-1-thread-3、1
pool-1-thread-2、7
pool-1-thread-3、2
pool-1-thread-2、8
pool-1-thread-3、3
pool-1-thread-2、9
pool-1-thread-3、4
pool-1-thread-3、5
pool-1-thread-3、6
pool-1-thread-3、7
pool-1-thread-3、8
pool-1-thread-3、9
对于4个线程,线程池创建了3个线程。
如果参数是Callable:
import java.util.concurrent.*;
class Mthread implements Runnable
{
@Override
public void run() {
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
class MCallThread implements Callable<String>
{
@Override
public String call() {
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+"、"+i);
}
return Thread.currentThread().getName()+"执行完毕";
}
}
public class TestExecutor {
public static void main(String[] args) {
MCallThread mthread=new MCallThread();
ExecutorService executorService=new ThreadPoolExecutor(
3,5,2000,TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>()); //创建线程池
for(int i=0;i<4;i++)
{
Future<String> future=executorService.submit(mthread);
try {
System.out.println(future.get()); //获取返回值
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
}
}
pool-1-thread-1、0
pool-1-thread-1、1
pool-1-thread-1、2
pool-1-thread-1、3
pool-1-thread-1、4
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-1、7
pool-1-thread-1、8
pool-1-thread-1、9
pool-1-thread-1执行完毕
pool-1-thread-2、0
pool-1-thread-2、1
pool-1-thread-2、2
pool-1-thread-2、3
pool-1-thread-2、4
pool-1-thread-2、5
pool-1-thread-2、6
pool-1-thread-2、7
pool-1-thread-2、8
pool-1-thread-2、9
pool-1-thread-2执行完毕
pool-1-thread-3、0
pool-1-thread-3、1
pool-1-thread-3、2
pool-1-thread-3、3
pool-1-thread-3、4
pool-1-thread-3、5
pool-1-thread-3、6
pool-1-thread-3、7
pool-1-thread-3、8
pool-1-thread-3、9
pool-1-thread-3执行完毕
pool-1-thread-1、0
pool-1-thread-1、1
pool-1-thread-1、2
pool-1-thread-1、3
pool-1-thread-1、4
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-1、7
pool-1-thread-1、8
pool-1-thread-1、9
pool-1-thread-1执行完毕
可以发现当一个线程执行完毕,才会执行另一个线程。因为FutureTask类执行任务只执行一次,并且会阻塞其他线程。Future.get( )会阻塞其他线程,一直等到当前Callable线程执行完毕拿到返回值为止。
五:JDK内置4大线程池
普通调度池:
- 创建无大小限制的线程池:Executors.newCachedThreadPoll( );
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
核心线程池大小为0,将线程放入无界阻塞队列中,根据线程任务快慢,调整线程数量:假如任务很快执行结束,创建线程很少,如果任务执行较长,会不断创建新线程。
适用于很多短期任务的小程序,负载较轻的服务器。
- 创建固定大小线程池:Executors.newFixedThreadPool(int nThreads) ,参数为线程数大小。
适用于为了满足资源管理的需求而需要限制当前线程数量的应用场合,适用于负载较重的服务器。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 单线程池:Executors. newSingleThreadExecutor( );从头到尾只有一个线程执行。
适用于需要保证顺序的执行各个任务,并且在任意时间点,不会有多个线程活动的场景。
定时调度池
Executors.newScheduledThreadPool( );
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
如:延迟执行一次
public class TestExecutor {
public static void main(String[] args) {
Mthread mthread = new Mthread();
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(3);
scheduledExecutorService.schedule(mthread, 3, TimeUnit.SECONDS);//3秒后开始执行
scheduledExecutorService.shutdown();
}
}
3秒后会执行一次。
定时器:
public class TestExecutor {
public static void main(String[] args) {
Mthread mthread = new Mthread();
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleAtFixedRate(mthread, 3, 2,TimeUnit.SECONDS);//3秒后开始执行
scheduledExecutorService.shutdown();
}
}
延迟3秒每隔两秒执行一次。
可以用scheduledExecutorService.scheduleAtFixedRate( )实现定时器。