スレッドプールの日常的な使用:
Messageクラス、スレッドプールを呼び出します
パブリッククラスMessageClientSendMsg { / ** *ロガー * / プライベート静的最終ログインLOGGER =新しいログ(MessageClientSendMsg.class)。 / ** *スレッドプール * / プライベート静的ExecutorServiceのスレッドプール。 / ** * 痕跡 * / プライベート文字列トレース。 / ** *電話番号 * / プライベート文字列cellNum。 / ** *メッセージエンティティ * / プライベートMessageProducerReqのmessageProducerReq。 静的{ スレッドプール= Executors.newFixedThreadPool(10);固定スレッドプールの//数 } / ** *コンストラクタ * * @Paramトレース要求水 * @Param cellNumの電話番号 * @Param messageProducerReqメッセージエンティティ * / 公共MessageClientSendMsg(文字列トレース文字列cellNum、MessageProducerReq messageProducerReq){ this.trace =トレース。 this.cellNum = cellNum。 this.messageProducerReq = messageProducerReq。 } / ** *メッセージを送ります * / ます。public void SENDMSG(){ SendMsgRunable sendMsgRunable =新しいSendMsgRunable(); threadPool.execute(sendMsgRunable)。 } / ** *送信メッセージクラスと内部処理が異常で、メインスレッドは、サービスに影響を与えることができません * / クラスSendMsgRunable実装Runnableを{ @オーバーライド ます。public void実行(){ {試します MessageClientProducer msgClintProducer =新しいMessageClientProducer(); msgClintProducer.sendAsyncWithPartition(トレース、cellNum、messageProducerReq)。 }キャッチ(例外e){ LOGGER.error(「メッセージが失敗した送信され、トレース:!」+トレース)。 } } } }
@EnableAsync注釈やメモを使用してスレッドプールを使用SpringBoot @Async
スレッド・プールを構成します:
輸入java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync パブリッククラスBeanConfig { @豆 公共のTaskExecutorのTaskExecutor(){ ThreadPoolTaskExecutorキュータ=新しいThreadPoolTaskExecutor(); //スレッドのコア数を設定します executor.setCorePoolSize(5)。 //スレッドの最大数を設定します executor.setMaxPoolSize(10)。 //キューの容量を設定します executor.setQueueCapacity(20)。 //セット(秒)スレッドアクティブ時間 executor.setKeepAliveSeconds(60)。 //設定されたデフォルトのスレッド名 executor.setThreadNamePrefix( "hello-"); //拒否ポリシーを設定します executor.setRejectedExecutionHandler(新しいThreadPoolExecutor.CallerRunsPolicy()); //スレッドプールの終了後にすべてのタスクの待ちが閉じられています executor.setWaitForTasksToCompleteOnShutdown(真の); executorを返します。 } }
同時操作:
輸入org.springframework.scheduling.annotation.Async; 輸入org.springframework.stereotype.Component; 輸入java.text.SimpleDateFormatの。 輸入java.util.Date; @成分 パブリッククラスTest { @Async ます。public voidテスト(I int型){ SimpleDateFormatのフォーマット=新しいてSimpleDateFormat( "HH:MM:SS"); {試します Thread.sleep(10000); System.out.println( "非同期実行をマルチスレッド" + I + ""。+にThread.currentThread()のgetName()+ "" + Format.format(新しいDate())); }キャッチ(InterruptedExceptionある電子){ e.printStackTrace(); } } }
コントローラ層の用途
@GetMapping( "/テスト") @ResponseBody 公共ボイド試験(){ 以下のために(; I <100、INT iが0 = I ++){ (i)はtest.test。 } }