一个java程序实现线程连接池功能

import java.util.LinkedList;

public abstract class Manager {

private String mThreadPoolName = null;

private int mThreadPoolMaxSize = 1;

private LinkedList workers = new LinkedList();

public Manager() {
}

public Manager(String name, int poolMaxSize) {
mThreadPoolName = name;
createWorker(name, poolMaxSize);
mThreadPoolMaxSize = poolMaxSize;
}

private void createWorker(int poolMaxSize) {
for (int i = 0; i < poolMaxSize; i++) {
Worker worker = new ...Worker(this);
workers.addLast(worker);
}
}

public synchronized Worker getIdleWorker() {
return (Worker)workers.removeFirst();
}

public synchronized void notifyFree(Worker worker) {
if (workers.size() < mThreadPoolMaxSize) {
workers.addLast(worker);
} else {
worker = null;
}
}

public int getThreadPoolMaxSize() {
return mThreadPoolMaxSize;
}

public void setThreadPoolMaxSize(int threadPoolMaxSize) {
this.mThreadPoolMaxSize = threadPoolMaxSize;
}

}

线程抽象类

public abstract class Worker implements Runnable {

private Manager mManager = null;

private Thread mThread = null;

public Worker() {
}

public Worker(String threadName, Manager manager) {
mManager = manager;
mThread = new Thread(this, threadName);
init();
mThread.start();
}

public abstract void init();

public void run() {
while (true) {
waitForStart();
Worker worker = mManager.getIdleWorker();
process();
isRunning = false;
mManager.notifyFree(worker);
}
}

public abstract void process();

public void start() {
isRunning = true;
mManager.getIdleWorker();
notifyToStart();
}

public synchronized void waitForStart() {
try {
wait();
} catch (InterruptedException ex) {
}
}

public synchronized void notifyToStart() {
notify();
}

}
转http://www.itzhuyi.com/Item/Show.asp?d=10268&m=1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值