java线程池

package com.ly.thread;

import java.util.LinkedList;

/**线程池
 * @author 牵手无奈
 * date:2015-10-14
 *
 */
public class ThreadPool extends ThreadGroup{

	private int poolSize;
	private static int threadPoolID;
	private boolean isClosed;
	private LinkedList<Runnable> workQueue;//工作任务队列
	private int ThreadID;
	
	
	public ThreadPool(int size){
		super("ThreadPool id="+threadPoolID++);
		this.poolSize=size;
		setDaemon(true);
		workQueue = new LinkedList<>();
		
		for(int i=0;i<poolSize;i++){
			new WorkThread().start();//先运行多个线程,随时准备通过它来执行任务
		}
	}
	
	/**执行提交的任务
	 * @param task
	 */
	public synchronized void execute(Runnable task){
		if(isClosed){
			throw new IllegalThreadStateException();
		}else{
			workQueue.add(task);
			notify();//唤醒在等待获取任务执行的线程
		}
	}
	
	
	public synchronized Runnable getTask() throws InterruptedException{
		while(workQueue.size()==0){
			if(isClosed) return null;
			wait();
			System.out.println("唤醒了一个线程");
		}
		
		return workQueue.removeFirst();
	}
	
	public synchronized void close(){
		if(!isClosed){
			isClosed=true;
			workQueue.clear();
		}
		interrupt();
	}
	
	public void join(){
		synchronized (this) {
			isClosed=true;
			notifyAll();
		}
		
		Thread[] threads = new Thread[activeCount()];
		int count = enumerate(threads);
		for(int i=0;i<count;i++){
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
	
	private class WorkThread extends Thread{
		
		public WorkThread(){
			super(ThreadPool.this,"WorkThread"+ThreadID++);
		}

		@Override
		public void run() {
			while (!isInterrupted()) {
				Runnable task = null;
				try {
					task=getTask();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(task==null){
					return;
				}else{
					task.run();
				}
			}
			
		}
		
	}
	
	
	public static void main(String[] args){
		ThreadPool tp = new ThreadPool(3);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		for( int i=0;i<10;i++){
			tp.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println("1");
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
		}
		tp.join();
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值