1、什么是线程池?
线程池:用来管理线程对象的池子
2、为什要使用线程池?
1、解决频繁的创建和销毁线程消耗的性能
2、解决大量创建线程而导致的内存泄露问题
注意: 一个线程大约占用内存1M
3、Java中是如何创建线程池
1、通过工具类完成线程池的创建【Executors】语法简单。但是阿里巴巴不建议使用
3.1、Executors中常用的方法:
-
-
static ExecutorService
newFixedThreadPool(int nThreads)创建一个固定的线程池 nTreads表示线程数量
-
-
-
static ScheduledExecutorService
newScheduledThreadPool(int corePoolSize)
创建一个延迟线程池。corePoolSize线程数量
-
-
-
static ExecutorService
newSingleThreadExecutor()创建一个单一线程池,即线程池中只有一个线程【适合任务按顺序执行的】
-
-
-
static ExecutorService
newCachedThreadPool()创建一个可变线程池【池子中线程数量会随着任务的大小而变化】
-
2、通过线程池类:ThreadPoolExecutor类。语法复杂,但是阿里巴巴建议使用。灵活
ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(10);
/**
* corePoolSize 初始化线程数量
* maximumPoolSize最大线程数
* keepAliveTime,线程维持时间
* TimeUnit unit 时间单位
* BlockingQueue<Runnable> workQueue 堵塞队列
*
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS,arrayBlockingQueue);
for (int i = 0; i <4 ; i++) {
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"=========");
}
});
}
}
3.2、ThreadPoolExecutor类中常用的方法
-
-
void
shutdown()有序关闭线程池,未执行完的任务将继续执行,但不接收新的任务
-
-
-
List<Runnable>
shutdownNow()立即关闭线程池,未执行的任务会以列表的形式返回
-
以下三种方法是AbstractExecutorService中实现ExecutorService接口中的方法
3.3 方法中Runnable参数的三种写法
1、创建实现了Runnable接口的类
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+"============"+i);
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
//创建一个类实现Runnable接口重新run方法
for (int i = 0; i <3 ; i++) {
executorService.execute(new MyRunnable());
}
}
}
2、匿名内部类
//2、匿名内部类
for (int i = 0; i <3 ; i++) {
executorService.execute(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"===============");
}
});
}
3、lamba表达上
//lambda表达式
for (int i = 0; i <3 ; i++) {
executorService.execute(()-> System.out.println(Thread.currentThread().getName()+"========="));
}
3.4 execite和submit方法的区别?
这两个方法都是用来执行线程任务,但是execute属于Executor类中的方法,而submit属于ExecutorService接口中的方法。而且submit可以执行runnable和callable类型的任务,而execute只能执行Runnable类型的任务。submit执行完任务后有返回结果
标签:Runnable,Java,int,创建,任务,线程,执行 From: https://blog.csdn.net/qq_58076226/article/details/140285079