ITeye博客

线程池的实现例子1

tobemoved · 2008-07-08 10:22 · java代码 · Markdown

import java.util.LinkedList; import java.util.List;

public class ThreadPool ...{

private static ThreadPool instance = null;

// 优先级低
public static final int PRIORITY_LOW = 0;

// 普通
public static final int PRIORITY_NORMAL = 1;

// 高
public static final int PRIORITY_HIGH = 2;

// 用以保存空闲连接
private List _idxThreads;

// 关闭
private boolean _shutdown = false;

// 线程数量
private int _threadCount = 0;

// debug信息是否输出
private boolean _debug = false;

/** *//**
 * 返回ThreadPool实例
 * 
 * @return
 */
public static ThreadPool getInstance() ...{
    if (instance == null) ...{
                instance = new ThreadPool();
        }
    return instance;
}

// 初始化线程list
private ThreadPool() ...{
    this._idxThreads = new List ...{ new LinkedList(), new LinkedList(),
            new LinkedList() };
    this._threadCount=0;
}

/** *//**
 * 同步方法,完成任务后将资源放回线程池中
 * @param repool
 */
protected synchronized void repool(Pooled repool) ...{
    if (this._shutdown) ...{
        if (this._debug) ...{
            System.out.println("ThreadPool.repool():重设中……");
        }
        // 优先级别判定
        switch (repool.getPriority()) ...{
        case Thread.MIN_PRIORITY:
            this._idxThreads.add(repool);
            break;
        case Thread.NORM_PRIORITY:
            this._idxThreads.add(repool);
            break;
        case Thread.MAX_PRIORITY:
            this._idxThreads.add(repool);
            break;
        default:
            throw new IllegalStateException("没有此种级别");
        }
        // 通知所有线程
        notifyAll();

    } else ...{
        if (this._debug) ...{
            System.out.println("ThreadPool.repool():注销中……");
        }
        repool.shutDown();
    }
    if(this._debug)...{
        System.out.println("ThreadPool.repool():完成");
    }
}
public void setDebug(boolean debug)...{
    this._debug=debug;
}
public synchronized  void shutDown()...{
    this._shutdown=true;
    if(this._debug)...{
        System.out.println("ThreadPool.shutDown():关闭中……");
    }
    for(int index=0;index<=PRIORITY_NORMAL;index++)...{
        List threads=this._idxThreads;
        for(int threadIndex=0;threadIndex<threads.size();threadIndex++)...{
            Pooled idleThread=(Pooled)threads.get(threadIndex);
            idleThread.shutDown();
        }
    }
    notifyAll();
}

/** *//**
 * 以指定的优先级启动线程
 * @param target
 * @param priority
 */
public synchronized void start(Runnable target,int priority)...{
    Pooled thread=null;
    List idleList=this._idxThreads;
    int idleSize=idleList.size();

    if(idleSize>0)...{
        int lastIndex=idleSize-1;
        thread=(Pooled)idleList.get(lastIndex);
        idleList.remove(idleList);
        thread.setTarget(target);
    }else...{
        this._threadCount++;
        thread=new Pooled(target,"Pooled->"+this._threadCount,this);
        switch(priority)...{
        
        case PRIORITY_LOW:
            thread.setPriority(Thread.MIN_PRIORITY);
            break;
        case PRIORITY_NORMAL:
            thread.setPriority(Thread.NORM_PRIORITY);
            break;
        case PRIORITY_HIGH:
            thread.setPriority(Thread.MAX_PRIORITY);
            break;
            default:
                thread.setPriority(Thread.NORM_PRIORITY);
        }
        //启动
        thread.start();

        }
    
    
}

/** *//**
 * 返回线程数量
 * 
 * @return
 */
public int getThreadsCount() ...{
    return this._threadCount;
}

}

Pooled.java: package org.loon.framework.util.test;

public class Pooled extends Thread ...{

private ThreadPool _pool;

private Runnable _target;

private boolean _shutdown = false;

private boolean _idle = false;

public Pooled(Runnable target) ...{
    super(target);
}

public Pooled(Runnable target, String name) ...{
    super(target, name);
}

public Pooled(Runnable target, String name, ThreadPool pool) ...{
    super(name);
    this._pool = pool;
    this._target = target;
}

public Pooled(String name) ...{
    super(name);
}

public Pooled(ThreadGroup group, Runnable target) ...{
    super(group, target);
}

public Pooled(ThreadGroup group, Runnable target, String name) ...{
    super(group, target, name);
}

public Pooled(ThreadGroup group, String name) ...{
    super(group, name);
}

public Runnable getTarget() ...{
    return this._target;
}

public boolean isIdle() ...{
    return this._idle;
}

public void run() ...{
    while (!this._shutdown) ...{
        this._idle = false;
        if (this._target != null) ...{
            this._target.run();
        }
        this._idle = true;
        try ...{

            this._pool.repool(this);

            synchronized (this) ...{
                wait();
            }

        } catch (InterruptedException ex) ...{
            System.err.println(ex.getMessage());
        }
        this._idle = false;
    }
}

public synchronized void setTarget(Runnable target) ...{
    this._target = target;
    notifyAll();
}

public synchronized void shutDown() ...{
    this._shutdown = true;
    notifyAll();
}

}

测试用类:

public class ThreadPoolTest ...{

private static Runnable createRunnable(final int id) ...{
    return new Runnable() ...{
        public void run() ...{
            System.out.println("线程" + id + ",运行 ");
            try ...{
                Thread.sleep(1000);
            }
            catch (InterruptedException ex) ...{ }
            System.out.println("线程" + id + ",结束");
        }
    };
}

public static void main(Stringargs)...{
    ThreadPool pool=ThreadPool.getInstance();
    pool.setDebug(true);
     for (int i=1; i<=10; i++) ...{
         //根据数值,设定不同优先级
         if(i%2==0)...{
                 pool.start(createRunnable(i), ThreadPool.PRIORITY_HIGH);
         }else...{
                 pool.start(createRunnable(i), ThreadPool.PRIORITY_LOW);
         }
     }
    System.out.println("线程池测试中……");
    System.out.println("线程池线程总数:"+pool.getThreadsCount());
    pool.shutDown();
}

}

评论(4)

  1. #4 楼 · helloguoxing · 2010-08-12 17:54

    //测试类的代码,我稍微改装了下。

    
    package com.soufang.test;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class ThreadPoolTest {
    
    	private static Runnable createRunnable(final int id){
    		return new Runnable(){
    			public void run(){
    				System.out.println("线程"+id+",运行");
    				try{
    					Thread.sleep(1000);
    				}catch(InterruptedException e){
    					System.out.println("线程"+id+",结束");
    				}
    			}
    		};
    	}
    	
    	public static void testThread(){
    		ThreadPool pool=ThreadPool.getInstance();
    		pool.setDebug(true);
    		for(int i=1;i<=10;i++){
    			//根据数值,设定不同优先级
    			if(i%2==0){
    				pool.start(createRunnable(i), ThreadPool.PRIORITY_HIGH);
    			}else{
    				pool.start(createRunnable(i), ThreadPool.PRIORITY_LOW);
    			}
    		}
    		//System.out.println("线程池线程总数:"+pool.getThreadsCount());
    		pool.shutDown();
    	}
    	
    	public static String read(){
    		String read="";
    		BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
    		try {
    			boolean bl=true;
    			while(bl){
    				read=buffer.readLine();
    				//关闭连接
    				if(read.contains(";")){
    					bl=false;
    				}
    			}
    				
    				
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		return read;
    	}
    	
    	public void toto(){
    		ThreadPool pool=ThreadPool.getInstance();
    		
    				String count=read();
    				if(""!=count && !"".equals(count)){
    					if(count.contains("1")){
    						testThread();
    						toto();
    					}else if(count.contains("2")){
    						pool.shutDown();
    						toto();
    					}else if(count.contains("3")){
    						System.out.println("线程池线程总数:"+pool.getThreadsCount());
    						toto();
    					}else if(count.contains("4")){
    						System.out.println("线程池测试中......");
    						toto();
    					}else if(count.contains("5")){
    						System.out.println("欢迎使用!");
    					}else{
    						System.out.println("请重新输入:1、启动线程 2、关闭线程 3、查询当前线程池所有线程数量 4、线程池当前状态 5、退出程序");
    						toto();
    					}
    				}
    	}
    	
    	public static void main(String[] args){
    		ThreadPoolTest threadtest=new ThreadPoolTest();
    		System.out.println("请重新输入:1、启动线程 2、关闭线程 3、查询当前线程池所有线程数量 4、线程池当前状态 5、退出程序");
    		threadtest.toto();
    		
    	}
    }
    
    
    
  2. #3 楼 · helloguoxing · 2010-08-12 17:53

    请重新输入:1、启动线程 2、关闭线程 3、查询当前线程池所有线程数量 4、线程池当前状态 5、退出程序 1 1; 线程2,运行 线程4,运行 线程6,运行 线程1,运行 线程8,运行 ThreadPool.shutDown();关闭中。。。。。。 线程10,运行 线程7,运行 线程5,运行 线程3,运行 线程9,运行 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 2; ThreadPool.shutDown();关闭中。。。。。。 3; 线程池线程总数:10 4; 线程池测试中...... 5; 欢迎使用! 5; 5;

    //唯一的问题,就是输入5的时候不能退出来。不知道楼主有没有发现。

  3. #2 楼 · helloguoxing · 2010-08-12 16:37

    请重新输入:1、启动线程 2、关闭线程 3、查询当前线程池所有线程数量 1 请重新输入:1、启动线程 2、关闭线程 3、查询当前线程池所有线程数量 线程2,运行 线程4,运行 线程6,运行 线程8,运行 线程池测试中...... 线程10,运行 线程池线程总数:10 ThreadPool.shutDown();关闭中。。。。。。 ThreadPool.shutDown();关闭中。。。。。。 线程1,运行 线程3,运行 线程5,运行 线程7,运行 线程9,运行 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成 ThreadPool.repool():重设中。。。。。。 ThreadPool.repool();完成

  4. #1 楼 · helloguoxing · 2010-08-12 16:36

    楼主这个线程池写的不错,我运行了下,优点略懂。

评论功能维护中,当前仅展示历史评论。