最近在看
线程池的类容,自己动手实现一个
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();
}
}
}