java中线程池_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java中线程池

java中线程池

 2016/6/27 5:31:28  LieutenantGeneral  程序员俱乐部  我要评论(0)
  • 摘要:最近在看线程池的类容,自己动手实现一个packagecn.RJ.utils;importjava.util.concurrent.LinkedBlockingQueue;importjava.util.concurrent.ThreadPoolExecutor;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.locks.Condition;importjava.util.concurrent.locks
  • 标签:Java 线程
最近在看线程池的类容,自己动手实现一个
class="java" name="code">
 package cn.RJ.utils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程池
 * @author RJ
 *
 */
public class MyThreadPool extends ThreadPoolExecutor {

	private static final int POOL_SIZE = 10;
	private boolean is_paused ;
	private ReentrantLock pause_lock = new ReentrantLock();
	private Condition unpaused = pause_lock.newCondition();
	
	public MyThreadPool(){
		super(POOL_SIZE,POOL_SIZE,0L,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(POOL_SIZE));
	}
	
	
	protected void beforeExecute(Thread t, Runnable r){
		super.beforeExecute(t, r);
		pause_lock.lock();
		try {
			while(is_paused){
				unpaused.await();
			}
		} catch (Exception e) {
			t.interrupt();
		}finally{
			pause_lock.unlock();
		}
	}
	
	
	public void pause(){
		pause_lock.lock();
		try {
			is_paused = true;
		}finally{
			pause_lock.unlock();
		} 
	}
	
	public void resume(){
		pause_lock.lock();
		try {
			is_paused = false;
			unpaused.signalAll();
		} finally{
			pause_lock.unlock();
		}
	}
		
}


发表评论
用户名: 匿名