1、基本概念
Java线程需要经过线程的创建,调用和销毁整个过程,频繁的创建和销毁会大大影响性能,所以引入的线程池:
好处:
- 提升性能:线程池能独立负责线程的创建、维护和分配
- 线程管理:每个Java线程池会保持一些基本的线程统计信息,对线程进行有效管理
2、JUC线程池架构
JUC指的是Java的并发工具包
1. Executor
Executor提供了execute()接口,用来执行已提交的Runnable目标实例,它只有1个方法:
void execute(Runnable command)
2. ExecutorService
继承于Executor.Java,异步目标任务的“执行者服务”接口,对外提供异步任务的接收服务
* @param task the task to submit
* @param <T> the type of the task's result
* @return a Future representing pending completion of the task
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if the task is null
*/
<T> Future<T> submit(Callable<T> task);//向线程池提交单个异步任务
//想线程池提交批量异步任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
3. AbstractExecutorService
抽象类,实现了ExecutorService
4. ThreadPoolExecutor
线程池实现类,继承于AbstractExecutorService,JUC线程池的核心实现类
5. ScheduledExecutorService
继承于ExecutorService。它是一个可以完成“延时”和“周期性”任务的调度线程池接口
6. ScheduledThreadPoolExecutor
继承于ThreadPoolExecutor,实现了ExecutorService中延时执行和周期执行等抽象方法
7. Executors
静态工厂类,它通过静态工厂方法返回ExecutorService、ScheduledExecutorService等线程池示例对象
3. Executors创建线程的4种方法
1. newSingleThreadExecutor创建“单线程化线程池”
package threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class CreateThreadPollDemo {
public static final int SLEEP_GAP=1000;
static class TargetTask implements Runnable{
static AtomicInteger taskNo=new AtomicInteger(1);
private String taskName;
public TargetTask()
{
taskName="task-"+taskNo;
taskNo.incrementAndGet();
}
public void run()
{
System.out.println("task:"+taskName+" is doing...");
try {
Thread.sleep(SLEEP_GAP);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task:"+taskName+" end...");
}
}
public static void main(String[] args) {
ExecutorService pool=Executors.newSingleThreadExecutor();
for(int i=0;i<3;i++)
{
pool.execute(new TargetTask());
pool.submit(new TargetTask());
}
pool.shutdown();
}
}
Java线程池(超详细)