单生产多消费

Posted divinehost

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单生产多消费相关的知识,希望对你有一定的参考价值。

package com.spider.utils;

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 int threadNum;

    private AtomicInteger threadAlive = new AtomicInteger();

    private ReentrantLock reentrantLock = new ReentrantLock();

    private Condition condition = reentrantLock.newCondition();

    private ExecutorService executorService;
    
    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;
    }

    public void execute(final Runnable runnable) {


        if (threadAlive.get() >= threadNum) {
            try {
                reentrantLock.lock();
                while (threadAlive.get() >= threadNum) {
                    try {
                        condition.await();
                    } catch (InterruptedException 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 pool = new CountableThreadPool(2);
       /* for(int i =0 ;i<100;i++){
            final int j = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(j%(j-3) +"   " + j);
                }
            });
        }*/
    }
}

以上是关于单生产多消费的主要内容,如果未能解决你的问题,请参考以下文章

java多线程:生产者和消费者模式(wait-notify) : 单生产和单消费

多消费者单生产者队列

Java实现多线程生产者消费模型及优化方案

单生产多消费

disruptor 单生产者多消费者

生产者消费者模型----------基于多进程多线程单线程并发