用户登录  |  傲看软件园 用户注册
文章中心广告代码ASP源码PHP源码JSP源码.NET源码源码相关傲看留言板繁體中文
当前位置:傲看软件园文章中心编程开发网络编程

用java实现一个线程连接池

减小字体 增大字体 作者:佚名  来源:本站整理  发布时间:2009-01-16 11:07:19
线程池:

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();
}

}

Tags:

作者:佚名

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论

精品栏目导航

关于本站 | 网站帮助 | 广告合作 | 下载声明 | 友情连接 | 网站地图
冀ICP备08004437号 | 客服Q:354766721 | 交流群83228313
傲看软件园 - 绿色软件,破解软件下载站! 源码网 源码之家 绿软之家
Copyright © 2003-2010 OkHan.Net. All Rights Reserved .
页面执行时间:4,562.50000 毫秒
Powered by:OkHan CMS Version 4.0.0 SP2