一,建立一個線程池java
其中:ide
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)this
飽和策略執行時的具體邏輯。spa
protected void afterExecute(Runnable r, Throwable t)線程
異常後的具體邏輯。日誌
package com.kintech.scanAF.common; import com.kintech.common.utils.log.LogerHelper; import java.util.concurrent.*; /** * @author Tyler * @date 2019/9/12 */ public class ThreadHelper { //初始化線程池 private static final ExecutorService pool = new ThreadPoolExecutor( 2, 5, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy(){ public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { LogerHelper.Write("--- "+this.getClass().getName()+"\r\n--- 隊列已滿,請稍後再來"); } }) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); LogerHelper.Write(t.getMessage()); System.out.println(t.getMessage()); } }; /** * 執行線程池方法(方法在RunnableFunc文件夾中) * @param run */ public static void execute(Runnable run) { pool.execute(run); } /** * 執行線程池方法(方法在RunnableFunc文件夾中) * @param run */ public static Future<?> submit(Runnable run) { Future<?> future = pool.submit(run); return future; } }
線程池的參數介紹:code
public ThreadPoolExecutor( int corePoolSize, // 線程數量 int maximumPoolSize, // 最大線程數量 long keepAliveTime, // 線程存活時間 TimeUnit unit, //時間單位 BlockingQueue<Runnable> workQueue, // 任務隊列 ThreadFactory threadFactory, // 線程建立工廠,能夠給線程起名字 RejectedExecutionHandler handler) // 飽和策略
二,建立任務blog
package com.kintech.scanAF.common.RunnableFunc; /** * @author Tyler * @date 2019/9/12 */ public class Test implements Runnable { private String a; public Test(String a) { this.a=a; } @Override public void run() { try { throw new RuntimeException( "Service has error !"); } catch (Exception e) { throw e; } finally { a=null; } } }
三,調用並獲取異常隊列
public void MainTest(String a) throws IOException { Future<?> future = ThreadHelper.submit(new Test(a)); try { future.get(); } catch (Exception ex) { //記錄日誌 LogerHelper.Write(ex.getMessage()); //swing彈窗 JOptionPane.showMessageDialog(null, ex.getMessage(), "Message", JOptionPane.ERROR_MESSAGE); } }