- package test.dao;
- import java.util.LinkedList;
- import org.apache.log4j.Logger;
- /**
- *
- * @author Andy.xiaomeng
- *
- */
- public class ThreadPool {
- private static final Logger Log = Logger.getLogger(ThreadPool.class);
- private ThreadWorker[] worker;
- private LinkedList<Runnable> queue;
- private int poolSize;
- public int getPoolSize(){
- return poolSize;
- }
- //initialize thread pool with pool size
- public ThreadPool(int size){
- poolSize = size;
- worker = new ThreadWorker[size];
- queue = new LinkedList<Runnable>();
- for (int i = 0; i < size; i++) {
- worker[i] = new ThreadWorker();
- worker[i].start();
- }
- }
- //add work queue
- public void addQueue(Runnable runnable){
- synchronized(queue) {
- queue.add(runnable);
- queue.notify();
- }
- }
- //worker do work
- private class ThreadWorker extends Thread{
- public void run(){
- //runnable
- Runnable runable;
- while (true) {
- synchronized(queue) {
- while (queue.isEmpty()) {
- try
- {
- //is work queue is empty, wait
- queue.wait();
- }
- catch (Exception e)
- {
- Log.error("pool queue wait", e);
- }
- }
- //get work in queue, and remove it
- runable = queue.removeFirst();
- }
- try {
- //do work
- runable.run();
- }
- catch (RuntimeException e) {
- Log.error("unknow runtime exception", e);
- }
- }
- }
- }
- public static void main(String[] args) {
- //test
- ThreadPool pool = new ThreadPool(111);
- //
- class SSS implements Runnable{
- private String abc;
- public void setAbc(String aaaaa){
- this.abc = aaaaa;
- }
- public void run() {
- System.out.println("do runnable " + abc);
- }
- }
- for (int i = 0; i < 200; i++) {
- SSS a = new SSS();
- a.setAbc(String.valueOf(i + 1));
- pool.addQueue(a);
- }
- }
- }
线程池管理
最新推荐文章于 2024-08-02 20:08:16 发布