`
vortexchoo
  • 浏览: 64068 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

简单的线程池

    博客分类:
  • java
 
阅读更多
package vortex.practise.Threads;

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

public class ThreadPool {
	
	//单例返回变量
	private static ThreadPool instance = null;
	//内部类数组
	private static InnerFactory[] IF;
	//线程池大小
	private static int poolSize = 0;
	//队列
	private static LinkedList<Runnable> queue = new LinkedList<Runnable>();
	
	//私有构造器
	private ThreadPool(){
	}
	//获得单例
	public static ThreadPool getNewInstance(){
		if(instance==null){
			instance = new ThreadPool();
		}
		return instance;
	}
	//创建线程池
        //根据传入的参数开启内部类的线程
	public void createPool(int size){
		this.poolSize = size;
		IF = new InnerFactory[size];
		for(int i=0;i<size;i++){
			IF[i] = new InnerFactory();
			IF[i].start();
		}
	}
	
//传入参数放置进入队列
	public void excuteThread(Runnable[] runs) throws Exception{
		if(poolSize==0){
			throw new Exception("please create poolSize!");
		}
		if(runs==null){
			throw new Exception("no parameters!");
		}else{
			for(Runnable run:runs){
				synchronized(queue){
					queue.addLast(run);
					queue.notify();
				}
			}
		}
	}
	
	/**
	 * 
	 * @author Vortex
	 *
	 * 
	 */
	private class InnerFactory extends Thread{

		public void run() {
			// TODO Auto-generated method stub
			Runnable r;
			int flag = 0;
			while(true){
				synchronized(queue){
					
					while(queue.isEmpty()){
						try {
							queue.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					r = queue.removeFirst();
					r.run();
				}
			}
		}
		
	}
}

 

 笔记。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics