赞
踩
首先,在服务启动的时候,我们可以启动好几个线程,并用一个容器(如线程池)来管理这些线程。当请求到来时,可以从池中取一个线程出来,执行任务(通常是对请求的响应),当任务结束后,再将这个线程放入池中备用;如果请求到来而池中没有空闲的线程,该请求需要排队等候。最后,当服务关闭时销毁该池即可。
public interface Pool {
//获取工作线程
public abstract PoolWorker getPoolWorker();
//销毁工作线程
public abstract void destroy();
}
public interface PoolWorker {
public abstract void setTask(Task task);
public abstract Task getTask();
public abstract void startTask();
}
public class Task {
public void execute() {
System.out.println("执行任务");
}
}
public class ThreadPoolManager implements Pool {
private boolean isShut;
private int size;
private LinkedList<PoolWorker> poolWorkers;
private class PoolWorkerImpl extends Thread implements PoolWorker {
private Task task;
private Object obj = new Object();
@Override
public void setTask(Task task) {
this.task = task;
}
@Override
public Task getTask() {
return this.task;
}
@Override
public void startTask() {
synchronized (obj) {
obj.notify();
}
}
public void run() {
while (!isShut) {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
getTask().execute();
synchronized (poolWorkers) {
poolWorkers.addFirst(PoolWorkerImpl.this);
poolWorkers.notifyAll();
}
}
}
}
public ThreadPoolManager(int size) {
this.size = size;
isShut = false;
poolWorkers = new LinkedList<PoolWorker>();
for (int i = 0; i < size; i++) {
PoolWorker poolWorker = new PoolWorkerImpl();
poolWorkers.add(poolWorker);
// 向下转型,以便可以使用子类独有的方法
((PoolWorkerImpl) poolWorker).start();
}
}
@Override
public PoolWorker getPoolWorker() {
PoolWorker poolWorker = null;
synchronized (poolWorkers) {
if (poolWorkers.size() > 0) {
poolWorker = poolWorkers.removeFirst();
} else {
try {
poolWorkers.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
poolWorker = poolWorkers.removeFirst();
}
}
return poolWorker;
}
@Override
public void destroy() {
isShut = true;
poolWorkers.notifyAll();
poolWorkers.clear();
}
}
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。