package pool;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* 固定的线程执行数
*/
public class ThreadPool
{
// 执行总线程
private List<Thread> list;
// 执行的最大线程数
private int max;
private ThreadTask task;
private Timer timer;
// 第一次执行的延迟时间
public static final long DELAY = 0;
// 重复执行的时间间隔,默认为 1秒
public static final long PERIOD = 1000;
// 正在此行的线程
private List<Thread> executing;
// 定时器消费者
private class ThreadTask extends TimerTask
{
@Override
public void run()
{
// 删除执行完的线程
removeDead(executing);
int count = executing.size();
// 执行小于max的线程
for (int i = count; i < max && list.size() > 0; i++)
{
Thread tread = list.remove(list.size() - 1);
executing.add(tread);
tread.start();
}
}
}
public ThreadPool(int max)
{
this.max = max;
list = Collections.synchronizedList(new LinkedList<Thread>());
executing = Collections.synchronizedList(new LinkedList<Thread>());
task = new ThreadTask();
// false非守护线程,true守护线程,守护线程的定义,当主线程关闭的时候守护线程同时不在执行,反之执行
timer = new Timer(false);
timer.schedule(task, DELAY, PERIOD);
}
// 生产者添加线程
public void excute(Thread thread)
{
list.add(thread);
}
// 取出执行完线程的引用
private void removeDead(List<Thread> list)
{
Thread thread = null;
for (int i = 0; i < list.size(); i++)
{
thread = list.get(i);
if (!thread.isAlive())
{
list.remove(i);
}
}
}
}
简陋线程池1
最新推荐文章于 2020-03-29 15:55:12 发布