首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

线程池二

2012-10-25 
线程池2package interview.pool2import interview.pool.ThreadPoolimport java.util.ArrayListimport j

线程池2

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();}}}}}

?

热点排行