package ThreadPool;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ThreadPool {
private BlockingQueue<Runnable> blockingQueue;
private int poolSize;
private int workSize;
public ThreadPool(int size)
{
poolSize = size;
workSize = 0;
blockingQueue = new LinkedBlockingQueue<Runnable>();
}
public synchronized void excute(Runnable t)
{
if(workSize == poolSize)
{
blockingQueue.add(t);
notify();
}
else
{
new Thread(new WorkThread("线程"+workSize,t)).start();
workSize = workSize + 1;
}
}
public synchronized Runnable getTask () throws InterruptedException
{
if(blockingQueue.size() == 0)
{
wait();
}
return blockingQueue.poll();
}
private class WorkThread implements Runnable
{
private String threadName;
private Runnable firstRunnable;
public WorkThread(String name,Runnable t)
{
this.firstRunnable = t;
this.threadName = name;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
if(firstRunnable != null)
{
System.out.println(threadName + "运行中");
firstRunnable.run();
firstRunnable = null;
}
else
{
Runnable runnable = getTask();
if(runnable == null)return;
System.out.println(threadName + "运行中");
runnable.run();
}
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
java线程池简单例子
最新推荐文章于 2015-12-04 23:16:00 发布