项目中遇到一个方法,方法中存在多个调用查询云端数据处理并且对每个查询的顺序有强制要求,针对此场景优化。
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 阻塞使任务可以按顺序执行