まず、スレッドプールを作成します
どこで:
公共ボイドrejectedExecution(RunnableをR、ThreadPoolExecutorエグゼキュータ)
具体的なロジック飽和ポリシーの施行。
保護された無効afterExecute(RunnableをR、Throwableをトン)
指定された論理例外の後。
パッケージcom.kintech.scanAF.common; 輸入com.kintech.common.utils.log.LogerHelper。 輸入 java.util.concurrentの*。; / ** * @author タイラー * @date 2019年9月12日 * / パブリック クラスThreadHelper { // 初始化线程池 プライベート 静的 最終 ExecutorServiceのプール= 新しいThreadPoolExecutor( 2 、 5 、 60 、 TimeUnit.SECONDS、 新しい ArrayBlockingQueue <Runnableを> (10)、 Executors.defaultThreadFactory()、 新ThreadPoolExecutor.DiscardPolicy(){ 公共 ボイドrejectedExecution(RunnableをR、ThreadPoolExecutorエグゼ){ LogerHelper.Write(「--- "+ この .getClass()。のgetName()+" \ rを\ N- -队列已满、请稍后再来」); } }) { @Overrideは、 保護された ボイドafterExecute(RunnableをR、のThrowable T){ スーパー.afterExecute(R、t)を。 LogerHelper.Write(t.getMessage())。 System.out.println(t.getMessage())。 } }。 / ** *スレッドプールの方法(方法RunnableFuncフォルダ) * @paramのRUN * / パブリック 静的 ボイド(RunnableをRUN)を実行 { pool.execute(RUN); } / ** *実行スレッドプールの方法(方法フォルダRunnableFunc )における * @paramのRUN * / パブリック 静的 <?>今後提出(RunnableをRUN) { 将来 <?>未来= pool.submit(RUN); 戻り未来; } }
導入されたスレッド・プールパラメータ:
公共ThreadPoolExecutor( int型 corePoolSize、// スレッドの数は int型 maximumPoolSize、// スレッドの最大数 ロング keepAliveTimeがを、// スレッドの生存期間 TimeUnitでユニット、// 時間単位 のBlockingQueue <Runnableを>ワークキュー、// タスクキュー ThreadFactory threadFactory、// スレッドの作成工場、名前スレッドできる のRejectedExecutionHandlerハンドラ)// 飽和戦略を
第二に、タスクを作成します
パッケージcom.kintech.scanAF.common.RunnableFunc; / ** * @author タイラー * @date 2019年9月12日 * / パブリック クラスのテストは実装したRunnable { プライベート文字列。 パブリックテスト(列A) { この .A = 。 } @Override 公共 ボイドラン(){ しようと { スロー 新しい(「サービスがエラーを持っている!」のRuntimeExceptionを)。 } キャッチ(例外e){ スローEと、 } 最後に { A = NULL ; } } }
第三に、例外を呼び出して取得します
公共 のボイド MainTest(文字列A)スローにIOException { 未来の未来= ThreadHelper.submit(<?> 新しいテスト(a)参照)。 試す{ future.getを(); } キャッチ(例外例) { // 记录日志 LogerHelper.Write(ex.getMessage())。 // スイング弹窗 JOptionPane.showMessageDialog(ヌル、ex.getMessage()、 "メッセージ" 、JOptionPane.ERROR_MESSAGE)。 } }