Java 线程池

    线程池能提高程序的并发能力。也容易导致与线程池有关的死锁、系统资源不足、线程泄漏、并发错误、任务过载等问题。

线程池代码:

package com.lyle.code;

import java.util.LinkedList;

/**
 * 线程池
 */
public class ThreadPool extends ThreadGroup {
	
	private boolean isClosed = false;	//线程池是否关闭
	private LinkedList<Runnable> workQueue;	//工作队列
	private static int threadPoolId;	//线程池ID
	private int threadId;	//线程ID
	

	public ThreadPool(int poolSize) {
		super("ThreadPool-"+(threadPoolId++));
		setDaemon(true);
		workQueue = new LinkedList<Runnable>();
		for(int i=0;i<poolSize;i++){
			new WorkThread().start();
		}
	}
	/**
	 * 向工作队列加入一个新任务,由工作线程去执行该任务
	 * @param task
	 */
	public synchronized void execute(Runnable task){
		if(isClosed){
			throw new IllegalStateException();
		}
		if(task!=null){
			workQueue.add(task);
			notify();
		}
	}
	
	/**
	 * 从工作队列中取出一个任务,工作线程会调用次方法
	 * @return
	 * @throws InterruptedException 
	 */
	private synchronized Runnable getTask() throws InterruptedException {
		while(workQueue.size()==0){
			if(isClosed){
				return null;
			}
			wait(); 	//如果队列中没有任务就等待
		}
		return workQueue.removeFirst();
	}
	
	/**
	 * 关闭线程池
	 */
	public void close(){
		if(!isClosed){
			isClosed=true;
			workQueue.clear();
			interrupt();	//中断所有工作线程,继承自ThreadGroup
		}
	}
	
	/**
	 * 等待所有线程把所有任务执行完成
	 */
	public void join(){
		synchronized (this) {
			isClosed=true;
			notify();
		}
		
		Thread[] threads=new Thread[activeCount()];
		
		int count = enumerate(threads);
		
		for(int i=0;i<count;i++){
			try{
				threads[i].join();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 内部类
	 * 
	 */
	private class WorkThread extends Thread{
		public WorkThread(){
			//加入到当前ThreadPool线程组中
			super(ThreadPool.this,"WorkThread-"+(threadId++));
		}
		
		public void run(){
			while(!isInterrupted()){
				Runnable task=null;
				try {
					task=getTask();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if(task==null){
					return;
				}
				task.run();
				
			}
		}

		
	}

}


测试:

package com.lyle.code;

public class ThreadPoolTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		ThreadPool threadPool=new ThreadPool(8);
		for(int i=0;i<15;i++){
			threadPool.execute(createTask(i));
		}
		threadPool.join();
	}

	private static Runnable createTask(final int task){
		return new Runnable() {
			public void run() {
				System.out.println("Task"+task+":start");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				System.out.println("Task"+task+":end");
			}
		};
	}
}


转载于:https://my.oschina.net/u/1767366/blog/295856

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值