java中线程池的实现【原创】

  前些天由于用到多线程处理,所以想到线程池,搜集了网上的一些资料,再分析改进一下,有了下面的东西。
  首先是个读取配置文件的类:

  1 None.gif package  org.ofbiz.smsSend;
  2 None.gif import  java.io.File;
  3 None.gif import  java.io.FileInputStream;
  4 None.gif import  java.io.FileNotFoundException;
  5 None.gif import  java.io.FileOutputStream;
  6 None.gif import  java.io.IOException;
  7 None.gif import  java.util.Properties;
  8 None.gif
  9 ExpandedBlockStart.gifContractedBlock.gif /** */ /**
 10InBlock.gif * @author zxub 2005-11-11 16:44:55
 11ExpandedBlockEnd.gif */

 12 None.gif
 13 None.gif public   class  UtilProperties
 14 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 15InBlock.gif
 16InBlock.gif    //设置默认的配置文件路径
 17InBlock.gif    private String fileName = System.getProperty("user.dir")
 18InBlock.gif            + "/base/config.properties";
 19InBlock.gif    private Properties prop;
 20InBlock.gif    private FileInputStream in;
 21InBlock.gif    private FileOutputStream out;
 22InBlock.gif
 23ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
 24InBlock.gif     * 自定义配置文件路径
 25InBlock.gif     * @param fileName
 26ExpandedSubBlockEnd.gif     */

 27InBlock.gif    public UtilProperties(String filePath)
 28ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{        
 29InBlock.gif        this.fileName = System.getProperty("user.dir")+filePath;
 30InBlock.gif        getFile();
 31ExpandedSubBlockEnd.gif    }

 32InBlock.gif
 33InBlock.gif    public UtilProperties()
 34ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 35InBlock.gif        getFile();
 36ExpandedSubBlockEnd.gif    }

 37InBlock.gif    
 38ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
 39InBlock.gif     * 获取配置文件
 40ExpandedSubBlockEnd.gif     */

 41InBlock.gif    private void getFile()
 42ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 43InBlock.gif        File file = new File(this.fileName);
 44InBlock.gif        try
 45ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 46InBlock.gif            in = new FileInputStream(file);
 47InBlock.gif            prop = new Properties();
 48InBlock.gif            // 载入文件
 49InBlock.gif            prop.load(in);
 50InBlock.gif            in.close();
 51ExpandedSubBlockEnd.gif        }

 52InBlock.gif        catch (FileNotFoundException e)
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 54InBlock.gif            System.err.println("配置文件config.properties找不到!!");
 55ExpandedSubBlockEnd.gif        }

 56InBlock.gif        catch (IOException e)
 57ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 58InBlock.gif            System.err.println("读取配置文件config.properties错误!!");
 59ExpandedSubBlockEnd.gif        }
        
 60ExpandedSubBlockEnd.gif    }

 61InBlock.gif
 62ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
 63InBlock.gif     * 列出所有的配置文件内容
 64ExpandedSubBlockEnd.gif     */

 65InBlock.gif    public void list()
 66ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 67InBlock.gif        prop.list(System.out);
 68ExpandedSubBlockEnd.gif    }

 69InBlock.gif
 70ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
 71InBlock.gif     * 指定配置项名称,返回配置值
 72InBlock.gif     * 
 73InBlock.gif     * @param itemName
 74InBlock.gif     *            String
 75InBlock.gif     * @return String
 76ExpandedSubBlockEnd.gif     */

 77InBlock.gif
 78InBlock.gif    public String getValue(String itemName)
 79ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 80InBlock.gif
 81InBlock.gif        return prop.getProperty(itemName);
 82InBlock.gif
 83ExpandedSubBlockEnd.gif    }

 84InBlock.gif
 85ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
 86InBlock.gif     * 设置配置项名称及其值
 87InBlock.gif     * 
 88InBlock.gif     * @param itemName
 89InBlock.gif     *            String
 90InBlock.gif     * @param value
 91InBlock.gif     *            String
 92ExpandedSubBlockEnd.gif     */

 93InBlock.gif
 94InBlock.gif    public void setValue(String itemName, String value)
 95ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 96InBlock.gif        prop.setProperty(itemName, value);
 97ExpandedSubBlockEnd.gif    }

 98InBlock.gif
 99ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
100InBlock.gif     * 保存配置文件,指定文件名和抬头描述
101InBlock.gif     * 
102InBlock.gif     * @param fileName
103InBlock.gif     *            String
104InBlock.gif     * @param description
105InBlock.gif     *            String
106InBlock.gif     * @throws Exception
107ExpandedSubBlockEnd.gif     */

108InBlock.gif    public void saveFile()
109ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
110InBlock.gif        try
111ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
112InBlock.gif            File f = new File(this.fileName);
113InBlock.gif            out = new FileOutputStream(f);
114InBlock.gif            prop.store(out, "");
115InBlock.gif            out.close();
116ExpandedSubBlockEnd.gif        }

117InBlock.gif        catch (FileNotFoundException e)
118ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
119InBlock.gif            e.printStackTrace();
120ExpandedSubBlockEnd.gif        }

121InBlock.gif        catch (IOException e)
122ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
123InBlock.gif            System.err.println("配置文件config.properties写入错误!!");
124ExpandedSubBlockEnd.gif        }

125InBlock.gif
126ExpandedSubBlockEnd.gif    }

127InBlock.gif
128ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
129InBlock.gif     * 删除一个属性
130InBlock.gif     * 
131InBlock.gif     * @param value
132InBlock.gif     *            String
133ExpandedSubBlockEnd.gif     */

134InBlock.gif
135InBlock.gif    public void deleteValue(String value)
136ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
137InBlock.gif        prop.remove(value);
138ExpandedSubBlockEnd.gif    }

139InBlock.gif    
140InBlock.gif    public void changeFile(String filePath)
141ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
142InBlock.gif        this.fileName = System.getProperty("user.dir")+filePath;
143InBlock.gif        getFile();
144ExpandedSubBlockEnd.gif    }

145InBlock.gif
146InBlock.gif    
147InBlock.gif    public static void main(String[] args)
148ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
149InBlock.gif        UtilProperties up = new UtilProperties();
150InBlock.gif        up.list();
151InBlock.gif        up.changeFile("/logs/config.properties");
152InBlock.gif        up.list();
153InBlock.gif        System.out.println("\n"+up.getValue("tmpSavePath"));
154ExpandedSubBlockEnd.gif    }

155InBlock.gif
156ExpandedBlockEnd.gif}

157 None.gif

  接着,是要做事的类,我写了一个接口,只有一个方法doWork(),在线程池中,一旦一个线程获得一个工作任务,线程就会调用工作任务的doWork()方法。
None.gif package  org.ofbiz.smsSend;
None.gif
None.gif
public   interface  Work
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public abstract void doWork();
ExpandedBlockEnd.gif}

None.gif
  然后,就是主要的线程池类了:
  1 ExpandedBlockStart.gif ContractedBlock.gif /** */ /**
  2InBlock.gif * @author zxub 2005-12-3 19:44:33
  3ExpandedBlockEnd.gif */

  4 None.gif package  org.ofbiz.smsSend;
  5 None.gif
  6 None.gif import  java.util.ArrayList;
  7 None.gif import  java.util.Iterator;
  8 None.gif import  java.util.LinkedList;
  9 None.gif import  java.util.Timer;
 10 None.gif
 11 None.gif public   class  ThreadPool
 12 ExpandedBlockStart.gifContractedBlock.gif dot.gif {    
 13InBlock.gif    private static final UtilProperties utilProp = new UtilProperties();
 14InBlock.gif    private static int minPools = Integer.parseInt(utilProp
 15InBlock.gif        .getValue("minPools"));
 16InBlock.gif    private static int maxPools = Integer.parseInt(utilProp
 17InBlock.gif        .getValue("maxPools"));
 18InBlock.gif    private static int checkThreadPeriod = Integer.parseInt(utilProp
 19InBlock.gif        .getValue("checkThreadPeriod")) * 60 * 1000;
 20InBlock.gif    private static ArrayList workThreadList; // 工作线程列表,保存所有的线程
 21InBlock.gif    private static LinkedList taskList = null// 工作任务列表,保存将要执行的工作任务
 22InBlock.gif    private static int totalThread = 0// 总线程数
 23InBlock.gif    private static int freeThreadCount = 0// 未被使用的线程数目
 24InBlock.gif    private java.util.Timer timer = null// 定时器
 25InBlock.gif    private static Object o = new Object();
 26InBlock.gif    
 27InBlock.gif    private static ThreadPool pool=new ThreadPool();
 28InBlock.gif    
 29InBlock.gif    public static void setMinPools(int minPools)
 30ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 31InBlock.gif        ThreadPool.minPools = minPools;
 32ExpandedSubBlockEnd.gif    }

 33InBlock.gif
 34InBlock.gif    public static void setMaxPools(int maxPools)
 35ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 36InBlock.gif        ThreadPool.maxPools = maxPools;
 37ExpandedSubBlockEnd.gif    }

 38InBlock.gif
 39InBlock.gif    public static void setCheckThreadPeriod(int checkThreadPeriod)
 40ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 41InBlock.gif        ThreadPool.checkThreadPeriod = checkThreadPeriod;
 42ExpandedSubBlockEnd.gif    }

 43InBlock.gif
 44InBlock.gif    private ThreadPool()
 45ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{        
 46InBlock.gif        workThreadList = new ArrayList();
 47InBlock.gif        taskList = new LinkedList();
 48InBlock.gif        //初始化线程池
 49InBlock.gif        for (int i = 0; i < ThreadPool.minPools; i++)
 50ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 51InBlock.gif            WorkerThread temp = new WorkerThread();
 52InBlock.gif            totalThread = totalThread + 1;
 53InBlock.gif            workThreadList.add(temp);
 54InBlock.gif            temp.start();
 55InBlock.gif            try
 56ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 57InBlock.gif                Thread.sleep(100);
 58ExpandedSubBlockEnd.gif            }

 59InBlock.gif            catch (Exception e)
 60ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 61ExpandedSubBlockEnd.gif            }

 62ExpandedSubBlockEnd.gif        }

 63InBlock.gif        timer = new Timer(true); // 启动定时器
 64InBlock.gif        timer.schedule(new CheckThreadTask(this), 0, checkThreadPeriod);
 65ExpandedSubBlockEnd.gif    }

 66InBlock.gif    
 67InBlock.gif    public static ThreadPool getInstance()
 68ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 69InBlock.gif        return pool;
 70ExpandedSubBlockEnd.gif    }

 71InBlock.gif    
 72InBlock.gif    public synchronized void run(Work work)
 73ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 74InBlock.gif        if (freeThreadCount == 0)
 75ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 76InBlock.gif            if (totalThread < maxPools)
 77ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 78InBlock.gif                WorkerThread temp = new WorkerThread();
 79InBlock.gif                totalThread = totalThread + 1;
 80InBlock.gif                workThreadList.add(temp);
 81InBlock.gif                temp.start();
 82InBlock.gif                synchronized (taskList)
 83ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 84InBlock.gif                    taskList.add(work);
 85InBlock.gif                    taskList.notify();
 86ExpandedSubBlockEnd.gif                }

 87ExpandedSubBlockEnd.gif            }

 88InBlock.gif            else
 89ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 90InBlock.gif                while (freeThreadCount == 0)
 91ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 92InBlock.gif                    try
 93ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
 94InBlock.gif                        Thread.sleep(200);
 95ExpandedSubBlockEnd.gif                    }

 96InBlock.gif                    catch (InterruptedException e)
 97ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
 98ExpandedSubBlockEnd.gif                    }

 99ExpandedSubBlockEnd.gif                }

100InBlock.gif                synchronized (taskList)
101ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
102InBlock.gif                    taskList.add(work);
103InBlock.gif                    taskList.notify();
104ExpandedSubBlockEnd.gif                }

105ExpandedSubBlockEnd.gif            }

106ExpandedSubBlockEnd.gif        }

107InBlock.gif        else
108ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
109InBlock.gif            synchronized (taskList)
110ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
111InBlock.gif                taskList.add(work);
112InBlock.gif                taskList.notify();
113ExpandedSubBlockEnd.gif            }

114ExpandedSubBlockEnd.gif        }

115ExpandedSubBlockEnd.gif    }

116InBlock.gif
117ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
118InBlock.gif     * 检查工作线程列表,将非活动状态的线程换成活动状态的线程,保证线程池中的线程可用
119InBlock.gif     *
120ExpandedSubBlockEnd.gif     */

121InBlock.gif    public synchronized void checkAllThreads()
122ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
123InBlock.gif
124InBlock.gif        Iterator threadIterator = workThreadList.iterator();
125InBlock.gif
126InBlock.gif        while (threadIterator.hasNext())
127ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif// 逐个遍厉
128InBlock.gif            WorkerThread workThread = (WorkerThread) threadIterator.next();
129InBlock.gif
130InBlock.gif            if (!(workThread.isAlive()))
131ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
132InBlock.gif                // 如果处在非活动状态时
133InBlock.gif                workThread = new WorkerThread(); // 重新生成1个线程
134InBlock.gif                workThread.start(); // 启动
135ExpandedSubBlockEnd.gif            }

136ExpandedSubBlockEnd.gif        }

137ExpandedSubBlockEnd.gif    }

138InBlock.gif
139InBlock.gif    public static void printInfo()
140ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
141InBlock.gif        System.out.println("minPools:" + minPools);
142InBlock.gif        System.out.println("maxPools:" + maxPools);
143InBlock.gif        System.out.println("checkThreadPeriod:" + checkThreadPeriod);
144InBlock.gif        System.out.println("totalThread=" + totalThread);
145InBlock.gif        System.out.println("workThreadList.size()=" + workThreadList.size());
146ExpandedSubBlockEnd.gif    }

147InBlock.gif   
148ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
149InBlock.gif     * 线程池中的工作线程类,由工作线程执行我们要进行的操作
150ExpandedSubBlockEnd.gif     */

151InBlock.gif    class WorkerThread extends Thread
152ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
153InBlock.gif        boolean running = true;
154InBlock.gif        Work work;
155InBlock.gif
156InBlock.gif        public void run()
157ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
158InBlock.gif            while (running)
159ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
160InBlock.gif                synchronized (o)
161ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
162InBlock.gif                    freeThreadCount++//一进来说明多了一个可用线程
163ExpandedSubBlockEnd.gif                }

164InBlock.gif                synchronized (taskList)
165ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
166InBlock.gif                    while (taskList.size() == 0//当工作任务列表为空时,等待
167ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
168InBlock.gif                        try
169ExpandedSubBlockStart.gifContractedSubBlock.gif                        dot.gif{
170InBlock.gif                            taskList.wait();
171InBlock.gif                            if (!running) return;
172ExpandedSubBlockEnd.gif                        }

173InBlock.gif                        catch (InterruptedException e)
174ExpandedSubBlockStart.gifContractedSubBlock.gif                        dot.gif{
175ExpandedSubBlockEnd.gif                        }

176ExpandedSubBlockEnd.gif                    }

177InBlock.gif                    synchronized (o)
178ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
179InBlock.gif                        freeThreadCount--//得到一个工作,可用线程要减1
180ExpandedSubBlockEnd.gif                    }

181InBlock.gif                    work = (Work) taskList.removeLast(); //从任务列表处获得一个任务
182InBlock.gif                    if (work == nullreturn;
183ExpandedSubBlockEnd.gif                }

184InBlock.gif                work.doWork();
185ExpandedSubBlockEnd.gif            }

186ExpandedSubBlockEnd.gif        }

187ExpandedSubBlockEnd.gif    }

188ExpandedBlockEnd.gif}

189 None.gif
  定时器自动查失效的线程,用到的方法如下:
 1 None.gif package  org.ofbiz.smsSend;
 2 None.gif
 3 None.gif import  java.util.TimerTask;
 4 None.gif
 5 None.gif public   class  CheckThreadTask  extends  TimerTask
 6 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 7InBlock.gif    private static boolean isRunning = false;
 8InBlock.gif    private ThreadPool pool;
 9InBlock.gif
10InBlock.gif    public CheckThreadTask(ThreadPool pool)
11ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
12InBlock.gif        this.pool = pool;
13ExpandedSubBlockEnd.gif    }

14InBlock.gif
15InBlock.gif    public void run()
16ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
17InBlock.gif        if (!isRunning)
18ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
19InBlock.gif            isRunning = true;
20InBlock.gif            pool.checkAllThreads();
21InBlock.gif            isRunning = false;
22ExpandedSubBlockEnd.gif        }

23ExpandedSubBlockEnd.gif    }

24ExpandedBlockEnd.gif}

25 None.gif
  最后,配置文件的内容如下
1 None.gif # ---------------- 线程池配置信息 -----------------
2 None.gif#
3 None.gif#线程池最小线程
4 None.gifminPools = 10
5 None.gif#线程池最大线程
6 None.gifmaxPools = 100
7 None.gif#检查线程池中线程的周期(分钟)
8 None.gifcheckThreadPeriod = 5
  ok,要用的时候,调用方法如下:
1 None.gif ThreadPool.getInstance().run( new  (实现了work接口的类));

转载于:https://www.cnblogs.com/zxub/archive/2005/12/09/293806.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值