使用ReentrantLock实现阻塞式的ThreadPoolExecutor

java 自带的ThreadPoolExecutor相关类里貌似没有阻塞式的提交(submit)

有需要的话得自己实现

以下是测试代码

package test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class BlockedExecuterPoolTest {

	static class BlockedThreadPoolExecutor extends ThreadPoolExecutor {
		private int submitCount = 0;
		public synchronized int getSubmitCount() {
			return submitCount;
		}
		public synchronized void setSubmitCount(int submitCount) {
			this.submitCount = submitCount;
		}
		public BlockedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
			super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
		}
		protected void afterExecute(Runnable r, Throwable t) {
			super.afterExecute(r, t);
			try {
				logger.info("unblock the canSubmit condition ");
				lock.lock();
				canSubmit.signal();
			} finally {
				if(submitCount>1){
					setSubmitCount(submitCount-1);
				}
				lock.unlock();
			}
		}

		final ReentrantLock lock = new ReentrantLock();
		Condition canSubmit = lock.newCondition();
		
		@Override
		public void execute(Runnable command) {
			try {
				lock.lockInterruptibly();
				while (getSubmitCount()>getMaximumPoolSize()) {
					logger.info("limit reached (getSubmitCount()["+getSubmitCount()+"]>getMaximumPoolSize()["+getMaximumPoolSize()+"]),thread["+Thread.currentThread().getName()+"] is being blocking");
					canSubmit.await();
				}
				super.execute(command);
				logger.info("blocking over");
			} catch (Exception e) {
				logger.warn(e.getLocalizedMessage());
			} finally {
				lock.unlock();
			}
		}
		
		@Override
		public Future<?> submit(Runnable task) {
			setSubmitCount(submitCount+1);
			return super.submit(task);
		}
	}

	static final Logger logger = Logger.getLogger(BlockedExecuterPoolTest.class);
	static final BlockedThreadPoolExecutor threadPoolExecutor = new BlockedThreadPoolExecutor(25, 25, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new RejectedExecutionHandler() {
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			logger.info("rejectedExecution!!!");
			System.exit(0);
		}
	});

	public static void main(String[] args) throws InterruptedException {
		int jobsAmount = 16166;
		logger.info("total ["+jobsAmount+"]"+"jobs awaits to be submitted");
		for (int i = 0; i < jobsAmount; i++) {
			String tag = "no." + i;
			logger.info("no.[" + tag + "] job is going to be submitted");
			threadPoolExecutor.submit(new TaskTest(tag));
			logger.info("no.[" + tag + "] job has been submitted:");
		}
		logger.info("total ["+jobsAmount+"]"+"jobs have been submitted");
	}

	public static class TaskTest implements Runnable {
		int jobTimeCost = 5000;
		public TaskTest(String string) {
			this.threadName = string;
		}
		String threadName;

		void sayBegin() {
			String s = "thread[" + this.threadName + "] is doing its job and it'll last for " + jobTimeCost + " milsecs";
			logger.info(s);
		}

		void sayEnd() {
			String s = "thread[" + this.threadName + "] has done its job and it last for " + jobTimeCost + " milsecs";
			logger.info(s);
		}

		@Override
		public void run() {
			sayBegin();
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				sayEnd();
			}
		}
	}
}



你可能感兴趣的:(java,多线程,线程池,锁,Lock)