求一份线程池的代码(分不是问题 可以追加)

城市拖拉机 2011-03-09 12:57:26
求一份线程池生成线程的代码、要在公司正式项目中使用过的、性能不会有问题的、分不是问题 可以追加!
...全文
62 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
0轰隆隆0 2011-03-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wang12 的回复:]

JDK5中已经加入了线程池类
java.util.concurrent.ThreadPoolExecutor
可以使用这个,没必要自己写了
[/Quote]
同意3楼
http://fulong258.blog.163.com/blog/static/17895044201082951820935/
大_爱 2011-03-09
  • 打赏
  • 举报
回复
我级别不高,只能简单写简单的,估计写出来不符合你的要求!
ilrxx 2011-03-09
  • 打赏
  • 举报
回复
同楼上,建议使用java.util.concurrent,大师写出来的东西性能一般都有保障
wang12 2011-03-09
  • 打赏
  • 举报
回复
JDK5中已经加入了线程池类
java.util.concurrent.ThreadPoolExecutor
可以使用这个,没必要自己写了
AldisZhan 2011-03-09
  • 打赏
  • 举报
回复
自己去研究^_^


import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

/** *//**
* 接受线程池管理的线程
*/
public class PooledThread extends Thread {

protected Vector tasks = new Vector();
protected boolean running = false;
protected boolean stopped = false;
protected boolean paused = false;
protected boolean killed = false;
private ThreadPool pool;

public PooledThread(ThreadPool pool){
this.pool = pool;
pool.threadCreated(this);
}

public void putTask(ThreadTask task) {
tasks.add(task);
}

public void putTasks(ThreadTask[] tasks) {
for(int i=0; i<tasks.length; i++)
this.tasks.add(tasks[i]);
}

protected ThreadTask popTask() {
if(tasks.size() > 0)
return (ThreadTask)tasks.remove(0);
else
return null;
}

public boolean isRunning() {
return running;
}

public boolean isTaskQueueEmpty() {
return tasks.isEmpty();
}

public void stopTasks() {
stopped = true;
}

public void stopTasksSync() {
stopTasks();
while(isRunning()) {
try {
sleep(5);
} catch (InterruptedException e) {
}
}
}

public void pauseTasks() {
paused = true;
}

public void pauseTasksSync() {
pauseTasks();
while(isRunning()) {
try {
sleep(5);
} catch (InterruptedException e) {
}
}
}

public void kill() {
if(!running)
interrupt();
else
killed = true;
}

public void killSync() {
kill();
while(isAlive()) {
try {
sleep(5);
} catch (InterruptedException e) {
}
}
}

public synchronized void activeThread() {
// 把线程从等待状态中激活,开始任务循环。
running = true;
pool.threadIdleStateChange(this, false);
this.notify();
}

public synchronized void run() {
try {
while(true) {
// 处理控制线程命令先。
if(killed) {
// 杀掉线程:向线程池任务队列转移自己所有任务,退出。
killed = false;
returnTaskToPool();
break;
}
if(stopped) {
// 停止线程:向线程池任务队列转移自己所有任务,然后等待。
stopped = false;
returnTaskToPool();
running = false;
}
if(paused) {
// 暂停线程,保持自己的任务队列,然后等待。
paused = false;
running = false;
}

ThreadTask task;
// 优先执行Thread自己的任务队列,再执行线程池中的任务队列。
if(running&&(task = pool.getTaskToRun())!=null){
task.run();
pool.taskCompleted();
}else if(running&&(task = popTask())!=null){
task.run();
// 该线程的任务包执行完毕,表示线程池中的一个大任务包执行完成。
if(tasks.size()==0)
pool.taskCompleted();
}else{
running = false;
pool.threadIdleStateChange(this, true);
this.wait();
}
}
}catch(InterruptedException e) {
// 在kill()方法中调用interrupt()方法,导致抛出此异常,结束线程。
// 非调试状态,注释掉让控制台输出clean
//e.printStackTrace();
return;
}finally{
returnTaskToPool();
tasks = null;
pool.threadDead(this);
}
}

private void returnTaskToPool() {
pool.taskReturnedFromThread(tasks);
tasks.clear();
}
}
AldisZhan 2011-03-09
  • 打赏
  • 举报
回复
哎好久不来 友情帮忙下 code 使用后果 概不负责 ^_^
啥解释不多少说 看 code


/**
* 线程任务
*/
public interface ThreadTask{
public void run();
}



import java.util.Collection;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/** *//**
* 线程池
*/
public class ThreadPool extends Timer{

public static final double LIMIT_IDLE = 0.75;
public static final double LIMIT_BUSY = 1.25;
public static final int POOL_STATE_HEALTHY = 0;
public static final int POOL_STATE_IDLE = 1;
public static final int POOL_STATE_BUSY = 2;

private static ThreadPool _instance = null;
protected int maxPoolSize = 10;
protected int initPoolSize = 2;
protected int tatolTaskNum = 0;
protected Vector tasksQueue = new Vector();
protected Vector allThreads = new Vector();
protected Vector idleThreads = new Vector();
protected boolean initialized = false;
protected boolean isRunnable = true;
protected int poolState = 0;

public static ThreadPool GetIntance(int maxPoolSize, int initPoolSize) {

if(_instance==null) {
_instance = new ThreadPool(maxPoolSize,initPoolSize);
}

return _instance;
}

public static ThreadPool GetIntance() {
if(_instance==null) {
_instance = new ThreadPool();
}

return _instance;
}

// 默认无参数构造函数。
protected ThreadPool() {
for(int i=0; i<initPoolSize; i++) {
PooledThread thread = new PooledThread(this);
thread.start();
}

initialized = true;

this.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
// TODO 自动生成方法存根
TimerEvent();
}

}, 1000, 1000);
}
protected ThreadPool(int maxPoolSize, int initPoolSize) {
if(maxPoolSize>0)
this.maxPoolSize = maxPoolSize;
if(initPoolSize>0)
this.initPoolSize = initPoolSize;
if(this.initPoolSize>this.maxPoolSize)
this.initPoolSize = this.maxPoolSize;

for(int i=0; i<initPoolSize; i++) {
PooledThread thread = new PooledThread(this);
thread.start();
}

initialized = true;

this.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
// TODO 自动生成方法存根
TimerEvent();
}

}, 1000, 1000);
}

private void TimerEvent() {

// 评定线程池健康状况

if(tatolTaskNum/allThreads.size()<LIMIT_IDLE)
poolState = POOL_STATE_IDLE;
else if(tatolTaskNum/allThreads.size()>LIMIT_BUSY){
poolState = POOL_STATE_BUSY;
}else
poolState = POOL_STATE_HEALTHY;



switch(poolState){
case POOL_STATE_IDLE:
{
// 杀掉线程池中过余的线程。
while(allThreads.size()>initPoolSize&&tatolTaskNum/allThreads.size()<LIMIT_IDLE) {
PooledThread th = getIdleThread(false);
if(th!=null){
th.kill();
}else{
break;
}
}
}
break;
case POOL_STATE_BUSY:
{
// 此处不用生成新线程,在加入新任务时会新增线程。
/*if(allThreads.size() < maxPoolSize) {
PooledThread thread = new PooledThread(this);
thread.start();
}*/
}
break;
case POOL_STATE_HEALTHY:
break;
default:
break;
}
}

public void setMaxPoolSize(int maxPoolSize) {
//System.out.println("重设最大线程数,最大线程数=" + maxPoolSize);
this.maxPoolSize = maxPoolSize;
if(maxPoolSize < getPoolSize())
setPoolSize(maxPoolSize);
}

/** *//**
* 重设当前线程数
* 若需杀掉某线程,线程不会立刻杀掉,而会等到线程中的事务处理完成
* 但此方法会立刻从线程池中移除该线程,不会等待事务处理结束
* @param size
*/
public void setPoolSize(int size) {
if(!initialized) {
initPoolSize = size;
return;
}else if(size > tatolTaskNum) {
for(int i=tatolTaskNum; i<size && i<maxPoolSize; i++) {
PooledThread thread = new PooledThread(this);
thread.start();
}
}else if(size < tatolTaskNum) {
while(getPoolSize() > size) {
PooledThread th = (PooledThread)allThreads.get(0);
th.kill();
}
}

//System.out.println("重设线程数,线程数=" + threads.size());
}

public int getPoolSize() {
return allThreads.size();
}

protected void threadCreated(PooledThread th) {
synchronized(allThreads) {
allThreads.add(th);
}
}

protected void threadDead(PooledThread th) {
synchronized(allThreads) {
threadIdleStateChange(th,false); // 如果空闲现成队列中还有引用,也清除掉。
allThreads.remove(th);
}
}
protected void threadIdleStateChange(PooledThread th,boolean isIdle) {
synchronized(idleThreads) {
if(isIdle)
idleThreads.add(th);
else
idleThreads.remove(th);
}
}

public PooledThread getIdleThread(boolean creatable) {
synchronized(idleThreads) {
if(!idleThreads.isEmpty())
return (PooledThread)idleThreads.remove(0);

// 新建一个线程。
if(creatable && getPoolSize() < maxPoolSize) {
PooledThread thread = new PooledThread(this);
thread.start();
return thread;
}

return null;
}
}

public ThreadTask getTaskToRun() {
synchronized(tasksQueue) {
if(tasksQueue.size()>0)
return (ThreadTask)tasksQueue.remove(0);
else
return null;
}
}

public void processTask(ThreadTask task) {
synchronized(tasksQueue) {
tasksQueue.add(task);
}
tatolTaskNum++;
// 默认的线程启动后都是等待状态,激活一个等待的闲置线程,让他自己去拿任务执行。
PooledThread th = getIdleThread(true);
if(th!=null)
th.activeThread();

}

public boolean processTasksInSingleThread(ThreadTask[] tasks) {
boolean isNewOrEmptyThreadToProcess = false;
PooledThread th = getIdleThread(true);

synchronized(tasksQueue) {
if(th!=null) {
if(th.isTaskQueueEmpty()) // 有空线程可以立即执行任务。
{
isNewOrEmptyThreadToProcess = true;
th.putTasks(tasks);
// 如果是交给单个线程处理,线程池任务总是只加1,这些任务当成打包处理。
tatolTaskNum++;
}else{
tasksQueue.add(tasks);
// 如果没有交给单个线程,线程池任务数加上实际数量。
tatolTaskNum+=tasks.length;
}

th.activeThread();
}else{
tasksQueue.add(tasks); // 暂时没有空线程来执行,先加入线程池任务队列中等待。
// 如果没有交给单个线程,线程池任务数加上实际数量。
tatolTaskNum+=tasks.length;
}
}

return isNewOrEmptyThreadToProcess;
}

public void taskCompleted(){
tatolTaskNum--;
}

public void taskReturnedFromThread(Vector tasks) {
tatolTaskNum--;
for(Iterator itr=tasks.iterator(); itr.hasNext();) {
ThreadTask task = (ThreadTask)itr.next();
processTask(task);
}

}

public int getMaxPoolSize() {
return maxPoolSize;
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧