使用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();
			}
		}
	}
}



转载于:https://my.oschina.net/u/560844/blog/403711

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值