package interview.pool2;
import interview.pool.ThreadPool;
import java.util.ArrayList;
import java.util.LinkedList;
public class ThreadPool2
{
// 线程数
public static int NUM = 5;
// 线程集合
private ArrayList threads = new ArrayList();
// 任务集合
private LinkedList<Task> tasks = new LinkedList<Task>();
private static final ThreadPool2 iNSTANCE = new ThreadPool2();
public static ThreadPool2 getInstance()
{
return iNSTANCE;
}
// 初始化
public ThreadPool2()
{
for (int i = 0; i < NUM; i++)
{
Worker worker = new Worker();
threads.add(worker);
worker.start();
}
}
/**
* 执行方法
*/
public void execute(Task task)
{
synchronized (tasks)
{
// 1. 加到任务队列最后面
tasks.addLast(task);
// 2.唤醒线程
tasks.notify();
}
}
/**
* 内部类:工作者线程
*/
private class Worker extends Thread
{
public void run()
{
// 局部变量更为合理
Task task;
while (true)
{
synchronized (tasks)
{
if (tasks.isEmpty())
{
try
{
tasks.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// 取出第一个任务执行
task = tasks.removeFirst();
}
// 必须将该方法提取到synchronized外面执行
try
{
task.execute();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
}