java-线程池Executor使用

项目中遇到一个方法,方法中存在多个调用查询云端数据处理并且对每个查询的顺序有强制要求,针对此场景优化。

demo

主类

package com.demo.thread.test20170804;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
	
	
	private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
	
	private static final int MAXIMUM_POOL_SIZE = 2 * CORE_POOL_SIZE + 1;

	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE), new TaskRejectedHandler());
		try {
			for (int i = 0; i < 10; i++) {
				executor.execute(new TaskRunnable("userName" + i, i));
			}
			
			executor.shutdown();
			
			//一直阻塞到任务完成
			while(!executor.awaitTermination(1, TimeUnit.SECONDS)) {
				System.out.println(executor.getMaximumPoolSize());
			}
			System.out.println("任务执行完毕");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("关闭");
			executor.shutdown();
		}
		
	}
}

任务

package com.demo.thread.test20170804;

import java.util.Random;

public class TaskRunnable implements Runnable{

	private String userName;
	private int status;
	
	public TaskRunnable(String userName, int status) {
		this.userName = userName;
		this.status = status;
	}
	
	@SuppressWarnings("static-access")
	@Override
	public void run() {
		Random random = new Random();
		System.out.println(Thread.currentThread().getName() + "======" + userName + "============" + status);
		try {
			Thread.currentThread().sleep(random.nextInt(100) * 100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

任务队列过多时处理

package com.demo.thread.test20170804;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class TaskRejectedHandler implements RejectedExecutionHandler{

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		try {
			executor.getQueue().put(r);
		} catch (Exception e) {
		}
	}

}

重点在于使用awaitTermination 阻塞使任务可以按顺序执行

转载于:https://my.oschina.net/u/3445128/blog/1502922

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值