간단한 스레드 풀

2039 단어 스레드 풀
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();
				}
			}
		}
		
	}
}

 
필기

좋은 웹페이지 즐겨찾기