【发布时间】:2023-02-20 18:40:01
【问题描述】:
我正在为作业创建一个线程池,如下所示。
public class MoveToCherwellThreadPool {
public static ThreadPoolExecutor cherwellMoveThreadPoolExecutor = null;
private static EMLogger logger = EMLogger.getLogger();
private static final String CLASSNAME = "MoveToCherwellThreadPool";
public static void initiateCherwellMoveThreadPool() {
BlockingQueue<Runnable> q = new LinkedBlockingQueue<Runnable>(100000);
cherwellMoveThreadPoolExecutor = new ThreadPoolExecutor(10,20, 20, TimeUnit.SECONDS, q);
cherwellMoveThreadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {
logger.logDebug(CLASSNAME,"Rejected task cherwellMoveThreadPoolExecutor Active tasks : " + cherwellMoveThreadPoolExecutor.getActiveCount() + ", " + "cherwellMoveThreadPoolExecutor Completed tasks : " + cherwellMoveThreadPoolExecutor.getCompletedTaskCount()+" Waiting for a second !! ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.execute(r);
}
});
}
}
我在为多个客户运行的过程中使用它。对于每个客户,新的线程池将被初始化并且线程将运行。 下面是我使用线程池的代码。
for (Object[] objects : relationshipList) {
CherwellRelationshipMoveThread relationshipThread = new CherwellRelationshipMoveThread(objects,
this.customerId, sb, credential,mainCIId,moveUniqueId,this.startTime);
CompletableFuture<?> future = CompletableFuture.runAsync(relationshipThread,
MoveToCherwellThreadPool.cherwellMoveThreadPoolExecutor);
crelationshipList.add(future);
}
crelationshipList.forEach(CompletableFuture::join);
将为多个客户创建此线程。我提供了在 UI 中终止此作业的选项。单击停止进程后,我只需要停止/终止为该特定客户运行的线程,而其他客户的线程不应受到损害,应继续运行。
单击 UI 中的停止进程时,我正在调用一个服务,我的代码将在服务内部
MoveToCherwellThreadPool.cherwellMoveThreadPoolExecutor.shutdownNow();
我在 ThreadPoolExecutor 上调用 shutdownNow()。
这正在杀死所有客户的所有线程。我不想终止所有客户进程,而只想终止我将单击停止进程的客户。
【问题讨论】:
标签: java multithreading java-8 thread-safety threadpool