服务端没接受一次任务就创建一个线程,如果成千上万次请求,那么将创建万计的线程,这样会导入服务器频繁的进行线程的切换,增加系统负担。
线程池技术能很好的解决这个问题。
- 消除了频繁创建和消亡线程的系统资源开销。
- 面对过量任务的提交能够平缓的劣化。
客户端线程将任务添加到任务队列jobs后就返回。工作者线程Worker不断从任务队列取出任务进行处理,当任务为空的时候,工作者线程等待,一旦有任务添加到队列,工作者线程立马被激活。
ThreadPool.java
package com.threadpooltest;
public interface ThreadPool<Job extends Runnable>{
//执行一个Job,这个job需要实现runnable
void execute(Job job);
//关闭线程池
void shutdown();
//增加工作者线程
void addWorkers(int num);
//减少工作者线程
void removeWorker(int num);
//得到正在等待执行的任务数量
int getJobSize();
}
DefaultThreadPool.java
package com.threadpooltest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
//线程池最大限制数
private static final int MAX_WORKER_NUMBERS = 10;
//线程池默认数量
private static final int DEFAULT_WORKER_NUMBER = 5;
//线程池最小数量
private static final int MIN_WORKER_NUMBER = 1;
//这是一个工作列表,将会向里面插入工作
private final LinkedList<Job> jobs = new LinkedList<Job>();
//工作者列表
//Collections.synchronizedList使非同步的集合变成同步的(我理解这样在多线程对该集合进行操作的时候就不用手动加锁了)。
private final List<Worker> workers = Collections.synchronizedList(new ArrayList<Worker>());
//工作者线程的数量
private int workerNum = DEFAULT_WORKER_NUMBER;
//线程编号生成
private AtomicLong threadNum = new AtomicLong();
public DefaultThreadPool(){
initializeWorkers(DEFAULT_WORKER_NUMBER);
}
public DefaultThreadPool(int num){
workerNum = num > MAX_WORKER_NUMBERS? MAX_WORKER_NUMBERS : num<MIN_WORKER_NUMBER?MIN_WORKER_NUMBER:num;
initializeWorkers(workerNum);
}
//初始化线程工作者
private void initializeWorkers(int num){
for(int i = 0; i<num; i++){
Worker worker = new Worker();
workers.add(worker);
Thread thread = new Thread(worker, "ThreadPool-Worker-" + threadNum.incrementAndGet() );//incrementAndGet原子的方式加一
thread.start();
}
}
@Override
public void execute(Job job) {
if(job != null){
//添加一个工作,然后进行通知
synchronized(jobs){
jobs.add(job);
jobs.notifyAll();
}
}
}
@Override
public void shutdown() {
for(Worker worker : workers){
worker.shutdown();
}
}
@Override
public void addWorkers(int num) {
synchronized(jobs){//这个加锁有必要用吗?我觉得这里不需要。
//限制新增的worker数量不能超过最大值
if(num + this.workerNum > MAX_WORKER_NUMBERS){
num = MAX_WORKER_NUMBERS - this.workerNum;
}
initializeWorkers(num);
this.workerNum += num;
}
}
@Override
public void removeWorker(int num) {
synchronized(jobs){
if(num >= this.workerNum){
throw new IllegalArgumentException("beyond worknum.");
}
//按照给定的数量停止worker
int count = 0;
while(count<num){
Worker worker = workers.get(count);
worker.shutdown();
count++;
}
this.workerNum -= num;
}
}
@Override
public int getJobSize() {
return jobs.size();
}
class Worker implements Runnable{
//是否工作
private volatile boolean running = true;
public void run() {
while(running){
Job job = null;
synchronized(jobs){
//如果工作者列表是空的,那么久wait
while(jobs.isEmpty()){
try {
jobs.wait();
} catch (InterruptedException e) {
//感知到外部对workerThread的中断操作,返回
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
//取出一个job
job = jobs.removeFirst();
}
if(job != null){
System.out.println(Thread.currentThread().getName() + "处理一个job。");
job.run();
}
}
}
public void shutdown(){
running = false;
}
}
}
ThreadPoolMain.java
package com.threadpooltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThreadPoolMain {
public static void main(String[] args) {
ThreadPool tp = new DefaultThreadPool<Task>();
int i = 0;
while(i++ < 7){
tp.execute(new Task());
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String command = "";
while(true){
try {
System.out.println("请输入指令:");
command = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(command.equals("quit")){
break;
}else if(command.equals("add")){
i = 0;
while(i++ < 7){
tp.execute(new Task());
}
}else if(command.equals("minus")){
}else if(command.equals("shutdown")){
tp.shutdown();
}
}
}
}
class Task implements Runnable{
@Override
public void run() {
System.out.println("Task 处理完毕!");
}
}