1.重复利用已创建的线程降低线程创建和销毁造成的消耗,因为线程的切换是有时间片上下文的切换。
2.提高响应速度,当任务到达时,无需等待线程的创建而直接运行
3.提高线程的可管理性,通过线程池进行统一的分配,管理与监控。
线程池类:ThreadPool
package com.yanbo.thread;
import java.util.List;
import java.util.Vector;
public class ThreadPool {
private static ThreadPool pool=null;//单利模式,创建对象
public int initSize;//初始线程池大小
public long timeout;//超时时间
public List
private ThreadPool(int initSize,long timeout){
this.initSize=initSize;
this.timeout=timeout;
for (int i = 0; i
}
}
public synchronized static ThreadPool getInstance(){
return getInstance(10,0);
}
public synchronized static ThreadPool getInstance(int initSize,long timeout){
if(pool==null){
pool=new ThreadPool(initSize, timeout);
}
return pool;
}
/**
* 添加任务
* @param target
*/
public void addWorker(Runnable target){
WorkThread worker=null;
if(workerList.size()>0){
worker=workerList.get(0);
workerList.remove(0);
worker.setTarget(target);
}else{
worker=new WorkThread(this, target);
workerList.add(worker);
}
}
/**
* 释放资源
* @param worker
*/
public void releaseWorker(WorkThread worker){
workerList.add(worker);
}
/**
* 关闭所有线程池
*/
public void shutdown(){
for (int i = 0; i
}
}
}
资源类:WorkThread
package com.yanbo.thread;
public class WorkThread extends Thread{
protected ThreadPool pool;
protected Runnable target;
private boolean isShutdown=false;//是否关闭
public void operate(){
System.out.println("========Now do database operate");
}
public WorkThread(ThreadPool pool) {
System.out.println("========初始化线程");
this.pool = pool;
}
public WorkThread(ThreadPool pool, Runnable target) {
System.out.println("<><><><>创建新线程<><><><>");
this.pool = pool;
this.target = target;
}
@Override
public void run() {
while(!isShutdown){
if(target!=null){
target.run();
}
pool.releaseWorker(this);
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public synchronized void setTarget(Runnable target){
this.target=target;
this.notifyAll();
}
public synchronized void shutdown(){
this.isShutdown=true;
}
}
工作线程:DoWork
package com.yanbo.thread;
public class DoWork implements Runnable{
@Override
public void run() {
int k=0;
for (int i = 0; i < 100; i++) {
k+=i;
}
System.out.println("结束。。。");
}
}
测试类:
package com.yanbo.thread;
import java.util.concurrent.CountDownLatch;
public class PoolTest {
public static void main(String[] args) {
long start=System.currentTimeMillis();
ThreadPool pool=ThreadPool.getInstance(20,1000);
for (int i = 0; i < 100; i++) {
pool.addWorker(new DoWork());
}
CountDownLatch count=new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
new Thread(new DoWork2(count)).start();
}
try {
count.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
/**线程池耗时4秒,而普通的线程耗时24秒**/
System.out.println("总共耗时:"+(System.currentTimeMillis()-start));
}
}