package pool;
public interface Request {
public void execute();
}
package pool;
public class HttpRequest implements Request {
private String name;
public HttpRequest(String name) {
super();
this.name = name;
}
@Override
public void execute() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println(Thread.currentThread().getName() + " 我执行了" + name + ".....");
}
}
package pool;
import java.util.LinkedList;
import java.util.Queue;
public class PoolManager {
private int maxSize;
private int maxTaskSize;
private LinkedList<WorkThread> workThreads = new LinkedList<WorkThread>();
private TaskQueue queue;
public PoolManager(int maxSize,int maxTaskSize) {
this.maxSize = maxSize;
this.maxTaskSize = maxTaskSize;
this.init();
}
private void init(){
queue = new TaskQueue(maxTaskSize);
for (int i = 0; i < maxSize; i++) {
WorkThread workThread = new WorkThread("工作线程" + i ,queue);
workThreads.add(workThread);
}
}
public void start() {
for (WorkThread workThread : workThreads) {
workThread.start();
}
}
public void execute(Request request) {
queue.addTask(request);
}
}
package pool;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class TaskQueue {
private int maxSize;
private Queue<Request> queue = new ConcurrentLinkedQueue<Request>();
public TaskQueue(int maxSize) {
super();
this.maxSize = maxSize;
}
public void addTask(Request request) {
synchronized (this) {
while(queue.size() >= maxSize) {
try {
System.err.println("任务队列已经满了。。。。。");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.err.println("添加新任务到任务队列中。。。。");
queue.add(request);
this.notifyAll();
}
}
public Request getTask() {
synchronized (this) {
while (queue.size() == 0) {
try {
System.err.println("当前任务队列为空.....");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Request request = queue.poll();
this.notifyAll();
return request;
}
}
}
package pool;
public class WorkThread extends Thread {
private TaskQueue queue;
private boolean used = false;
public boolean isUsed() {
return used;
}
public WorkThread(String name,TaskQueue queue) {
this.queue = queue;
this.setName(name);
}
@Override
public void run() {
while (true) {
used = true;
Request task = queue.getTask();
task.execute();
used = false;
}
}
}