項目中遇到一個方法,方法中存在多個調用查詢雲端數據處理而且對每一個查詢的順序有強制要求,針對此場景優化。java
demodom
主類ide
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(); } } }
任務隊列過多時處理this
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 阻塞使任務能夠按順序執行code