一个精简的线程池实现

goes_kad 2005-07-01 02:25:55
package com.xnull.threads ;

import java.util.List ;
import java.util.ArrayList ;

/**
* @author Xiongkq
* @version 1.0
*/
public class SimpleThreadPool
{
private int maxThreads ;
private List taskList ;
private int threadCount ;
private int freeCount ;
private boolean shutdown ;

public SimpleThreadPool ()
{
this ( 0 , 5 ) ;
}

public SimpleThreadPool ( int initThreads , int maxThreads )
{
taskList = new ArrayList () ;
this.maxThreads = maxThreads ;
createWorker ( initThreads ) ;
}

public synchronized void shutdown ()
{
if ( !shutdown )
{
shutdown = true ;
notifyAll () ;
}
}

public synchronized void addTask ( Runnable task )
{
taskList.add ( task ) ;
checkWorkers () ;
notify () ;
}

private synchronized void gainFreeThead ()
{
freeCount++ ;
}

private synchronized void reduceFreeThead ()
{
freeCount-- ;
}

private void checkWorkers ()
{
int allowCreateCount = maxThreads - threadCount ;
int createCount = taskList.size () - freeCount ;
if ( createCount > allowCreateCount )
{
createCount = allowCreateCount ;
}

if ( createCount > 0 )
{
createWorker ( createCount ) ;
}
}

private void createWorker ( int createCount )
{
threadCount += createCount ;
freeCount += createCount ;
for ( int i = 0 ; i < createCount ; i++ )
{
new WorkerThread ().start () ;
}
}

private synchronized void notifyThreadDeath ( WorkerThread worker )
{
threadCount-- ;
checkWorkers () ;
}

private synchronized Runnable getTask ()
{
while ( taskList.size () == 0 )
{
try
{
wait () ;
}
catch ( InterruptedException ex )
{
return null ;
}
}

if ( shutdown )
{
return null ;
}

return ( Runnable ) taskList.get ( 0 ) ;
}

class WorkerThread
extends Thread
{
public void run ()
{
while ( true )
{
gainFreeThead () ;
Runnable run = getTask () ;
if ( run != null )
{
reduceFreeThead () ;
try
{
run.run () ;
}
catch ( Throwable ex )
{
notifyThreadDeath ( this ) ;
break ;
}
}
else
{
if ( shutdown )
{
break ;
}
}
}
}
}
}
...全文
220 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
huzhangyou 2006-05-21
  • 打赏
  • 举报
回复
鼓励一下~~~
dfchjk 2006-05-21
  • 打赏
  • 举报
回复
mark
Wolf0403 2006-05-21
  • 打赏
  • 举报
回复
用 java.util.concurrent 的 ThreadPoolExecutor 吧

62,614

社区成员

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

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