一、线程池简介
1. 线程池的概念:
所谓的线程池指的就是多个线程封装在一起进行操作。使用线程池可以很好地提高性能,线程池在系统启动时即创建大量空闲的线程,程序将一个任务传给线程池,线程池就会启动一条线程来执行这个任务,执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。
2. 线程池的工作机制
2.1 在线程池的编程模式下,任务是提交给整个线程池,而不是直接提交给某个线程,线程池在拿到任务后,就在内部寻找是否有空闲的线程,如果有,则将任务交给某个空闲的线程。
2.1 一个线程同时只能执行一个任务,但可以同时向一个线程池提交多个任务。
3. 使用线程池的原因:
多线程运行时间,系统不断的启动和关闭新线程,成本非常高,会过渡消耗系统资源,以及过渡切换线程的危险,从而可能导致系统资源的崩溃。这时,线程池就是最好的选择了。
二、四种常见线程池示例
1.CacheThreadPool
package com.leo.thread.executorPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CacheThreadPoolDemo {
public static void main(String[] args) {
//创建一个可缓存线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
try {
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
//打印正在执行的缓存线程信息
System.out.println(Thread.currentThread().getName()+" 正在被执行 ");
}
});
//sleep可明显看到使用的是线程池里面以前的线程,没有创建新的线程
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cachedThreadPool.shutdown();
}
}
执行结果:
当然,您也可以将Thread.sleep(0)试试效果。
2.FixedThreadPool
package com.leo.thread.executorPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPoolDemo {
public static void main(String[] args) {
//创建一个可重用固定个数的线程池,以共享的无界队列方式来运行这些线程
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
//因为线程池大小为3,每个任务输出打印结果后sleep 1秒,所以每秒打印3个结果。
System.out.println(Thread.currentThread().getName()+"正在被执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
fixedThreadPool.shutdown();
}
}
执行结果:
3.ScheduledThreadPool
package com.leo.thread.executorPool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolDemo {
public static void main(String[] args) {
//创建一个定长线程池,支持定时3秒后执行任务——延迟执行
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
for (int i = 0; i < 10; i++) {
//延迟3秒后执行
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 正在执行");
}
},3, TimeUnit.SECONDS);
}
scheduledThreadPool.shutdown();
}
// public static void main(String[] args) {
// //创建一个定长线程池,支持定时及周期性任务执行——延迟执行
// ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
// for (int i = 0; i < 10; i++) {
// //延迟3秒后执行
// scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName()+" 正在执行");
//
// }
// },1,3, TimeUnit.SECONDS);
// }
// scheduledThreadPool.shutdown();
// }
}
3秒后执行完毕,注释部分是想使用定时及周期执行。
4.SingleThreadExecutor
package com.leo.thread.executorPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorDemo {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"正在执行");
}
});
}
singleThreadExecutor.shutdown();
}
}
执行结果:
顾名思义,只有单条线程执行任务。
三、ThreadPoolExecutor
1.ThreadPoolExecutorDemo
package com.leo.thread.executorPool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorDemo {
public static void main(String[] args) throws InterruptedException {
RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
2,
4,
10,
TimeUnit.SECONDS,
//new ArrayBlockingQueue<Runnable>(2),
new LinkedBlockingQueue<Runnable>(2),
threadFactory,
rejectionHandler);
MyThread myThread = new MyThread(threadPoolExecutor, 3);
Thread thread = new Thread(myThread);
thread.start();
for (int i = 0; i < 10; i++) {
threadPoolExecutor.execute(new WorkerThread("cmd"+i));
}
Thread.sleep(30000);
//shut down the pool
threadPoolExecutor.shutdown();
//shut down the monitor thread
Thread.sleep(5000);
myThread.shutdown();
}
}
2.RejectedExecutionHandlerImpl
package com.leo.thread.executorPool;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler{
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + " is rejected");
}
}
3.MyThread
package com.leo.thread.executorPool;
import java.util.concurrent.ThreadPoolExecutor;
public class MyThread implements Runnable{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run = true;
public MyThread(ThreadPoolExecutor executor, int seconds) {
super();
this.executor = executor;
this.seconds = seconds;
}
public void shutdown() {
this.run = false;
}
@Override
public void run() {
while(run) {
System.out.println(
String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4.WorkerThread
package com.leo.thread.executorPool;
public class WorkerThread implements Runnable{
private String command;
public WorkerThread(String command) {
super();
this.command = command;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
执行结果:
着重看执行顺序,看完再对照下本人之前讲的基本概念,那么你对线程池的概念记忆应该会更加深刻。
详细介绍ThreadPoolExecutor:https://blog.csdn.net/u012829233/article/details/85701402
四、缓冲队列BlockingQueue和自定义线程池ThreadPoolExecutor
1. 缓冲队列BlockingQueue简介:
BlockingQueue是双缓冲队列。BlockingQueue内部使用两条队列,允许两个线程同时向队列一个存储,一个取出操作。在保证并发安全的同时,提高了队列的存取效率。
2. 常用的几种BlockingQueue:
-
ArrayBlockingQueue(int i):规定大小的BlockingQueue,其构造必须指定大小。其所含的对象是FIFO顺序排序的。
-
LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其构造时指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE来决定。其所含的对象是FIFO顺序排序的。
-
PriorityBlockingQueue()或者(int i):类似于LinkedBlockingQueue,但是其所含对象的排序不是FIFO,而是依据对象的自然顺序或者构造函数的Comparator决定。
-
SynchronizedQueue():特殊的BlockingQueue,对其的操作必须是放和取交替完成。
其中,LinkedBlockingQueue和ArrayBlockingQueue类似,不过前者性能更高。