线程池代表一组执行任务的工作线程,每个线程可以多次重用。如果在所有线程都处于活动状态时提交了新任务,则它们将在队列中等待,直到线程可用。 线程池实现在内部使用LinkedBlockingQueue向队列添加和删除任务。我们通常想要的是一个工作队列与一组固定的工作线程相结合,它使用wait()和notify()来表示新工作已到达的等待线程。 介绍完线程池原理,我们来介绍如何用ExecutorService来实现线程池。
ReentrantLock
ReentrantLock是一种独占锁,只能有一个线程获取锁,并且一个线程可以多次lock。ReentrantLock提供公平锁与非公平锁,默认非公平锁,
ReentrantLock是Lock接口的默认实现。 lock接口定义
public interface Lock {
//上锁(不响应Thread.interrupt()直到获取锁)
void lock();
//上锁(响应Thread.interrupt())
void lockInterruptibly() throws InterruptedException;
//尝试获取锁(以nonFair方式获取锁)
boolean tryLock();
//在指定时间内尝试获取锁(响应Thread.interrupt(),支持公平/二阶段非公平)
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
//解锁
void unlock();
//获取Condition
Condition newCondition();
}
复制代码
代码实现
import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class CountableThreadPool {
private Logger logger = LoggerFactory.getLogger(getClass());
private int threadNum;
private int threadNum; //固定线城池大小
private AtomicInteger threadAlive = new AtomicInteger(); //活动线程计数
private Condition condition = reentrantLock.newCondition();
public CountableThreadPool(int threadNum) {
this.threadNum = threadNum;
this.executorService = Executors.newFixedThreadPool(threadNum);
}
public CountableThreadPool(int threadNum, ExecutorService executorService) {
this.threadNum = threadNum;
this.executorService = executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
public int getThreadAlive() {
return threadAlive.get();
}
public int getThreadNum() {
return threadNum;
}
private ExecutorService executorService;
public void execute(final Runnable runnable) {
if (threadAlive.get() >= threadNum) {
try {
reentrantLock.lock();
while (threadAlive.get() >= threadNum) {
try {
condition.await();
} catch (InterruptedException e) {
logger.error(Throwables.getStackTraceAsString(e));
}
}
} finally {
reentrantLock.unlock();
}
}
threadAlive.incrementAndGet();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} finally {
try {
reentrantLock.lock();
threadAlive.decrementAndGet();
condition.signal();
} finally {
reentrantLock.unlock();
}
}
}
});
}
public boolean isShutdown() {
return executorService.isShutdown();
}
public void shutdown() {
executorService.shutdown();
}
public static void main(String[] args) {
CountableThreadPool threadPool = new CountableThreadPool(10);
for(int i = 0;i < 10; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
//TODO
}
});
}
}
}
复制代码