线程池表明一组执行任务的工做线程,每一个线程能够屡次重用。若是在全部线程都处于活动状态时提交了新任务,则它们将在队列中等待,直到线程可用。 线程池实如今内部使用LinkedBlockingQueue向队列添加和删除任务。咱们一般想要的是一个工做队列与一组固定的工做线程相结合,它使用wait()和notify()来表示新工做已到达的等待线程。 介绍完线程池原理,咱们来介绍如何用ExecutorService来实现线程池。java
ReentrantLock是一种独占锁,只能有一个线程获取锁,而且一个线程能够屡次lock。ReentrantLock提供公平锁与非公平锁,默认非公平锁,ide
ReentrantLock是Lock接口的默认实现。 lock接口定义this
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
}
});
}
}
}
复制代码