利用ExecutorService实现线程池

本文介绍了线程池的基本原理及其实现方法,并详细解释了ReentrantLock的使用方式及其特性。通过一个具体的CountableThreadPool类实例,展示了如何结合线程池和ReentrantLock进行并发控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程池代表一组执行任务的工作线程,每个线程可以多次重用。如果在所有线程都处于活动状态时提交了新任务,则它们将在队列中等待,直到线程可用。 线程池实现在内部使用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
                }
            });
        }
    }

}
复制代码

转载于:https://juejin.im/post/5ca5ced1f265da309d08a395

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值