当前位置:网站首页>About terminating tasks in thread pool
About terminating tasks in thread pool
2022-07-19 05:40:00 【Spring and autumn of Qin and Han Dynasties】
Use the thread pool itself to delete or terminate tasks , There is a necessary premise :
The task must exist in the queue .
Why do you say that? ?
Because what we call “ Delete task ” Refer to ThreadPoolExecutor Of remove Method :
public boolean remove(Runnable task) {
boolean removed = workQueue.remove(task);
tryTerminate(); // In case SHUTDOWN and now empty
return removed;
}
You can see , It's from workQueue Removed from ;
in other words , If the task has been run , Theoretically, you cannot use thread pool to delete .
such as :
private static void testNormalRemove() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3));
Thread task1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("normal1," + Thread.currentThread().getId());
}
}
});
Thread task2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("normal2," + Thread.currentThread().getId());
}
}
});
tpe.execute(task1);
tpe.execute(task2);
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tpe.getQueue().size());
System.out.println("remove task2," + tpe.remove(task2));
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Here you are task1、task2 Two tasks , The core thread of the created thread pool is 1, that task1 It will be run immediately after being added , and task2 Will be added to the queue waiting to run , The principle can refer to Analysis of the principle of thread pool , that task2 Yes, it can be. remove The success of , and task1 Can't be remove Of , because Not in the queue at all 了 .
Of course , There are some special thread pools , Each task is actually added to the queue , such as ScheduledThreadPoolExecutor When adding tasks , In fact, every task is added to the queue :
public void execute(Runnable command) {
schedule(command, 0, NANOSECONDS);
}
public ScheduledFuture<?> schedule(Runnable command,
long delay,
TimeUnit unit) {
if (command == null || unit == null)
throw new NullPointerException();
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Void>(command, null,
triggerTime(delay, unit)));
delayedExecute(t);
return t;
}
private void delayedExecute(RunnableScheduledFuture<?> task) {
if (isShutdown())
reject(task);
else {
super.getQueue().add(task);
if (isShutdown() &&
!canRunInCurrentRunState(task.isPeriodic()) &&
remove(task))
task.cancel(false);
else
ensurePrestart();
}
}
In this way, the added tasks can be deleted ;
Of course, it should be noted that the added tasks are encapsulated RunnableScheduledFuture, So remember to convert to RunnableScheduledFuture Then delete , If using schedule Or others scheduleXX Method , Will go straight back to RunnableScheduledFuture, You can delete the returned value .
Other thread pools are not so “ Good luck ” 了 , Follow the general rules , Only in excess of corePoolSize Will join the queue ;
There is a method to stop threads inside the thread pool , But the scheduling methods inside the thread pool are mostly private, Cannot be called , Like this :
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
workers.remove(w);
} finally {
mainLock.unlock();
}
// A little
}
Threads or tasks that have been run are encapsulated as Worker, But about Worker Our method is not open to the public , This is also the reason why most thread pools cannot finely control threads —— Of course , Threads themselves are very fine-grained .
On the whole , Once the thread starts , It is difficult to stop by conventional means , It is often necessary to throw exceptions or add return Or force interrupt To stop ;
If you need to master threads , Then the use is similar to ScheduledThreadPoolExecutor Thread pool is also a good choice in some scenarios .
边栏推荐
猜你喜欢

Ambari 2.7.5 integrated installation hue 4.6

10.数据仓库搭建之DWD层搭建

电商用户行为实时分析系统(Flink1.10.1)

Spark core programming (4) -- spark operation architecture

10. DWD layer construction of data warehouse construction

C language & bit field

8. ODS layer construction of data warehouse

2. Technology selection of Neusoft cross border e-commerce data warehouse project

软件过程与管理复习(七)

How can the thread pool be monitored to help developers quickly locate online errors?
随机推荐
Custom components of wechat applet
东软跨境电商数仓开发进度
Use ide to make jar package
安卓实现真正安全的退出app
尝试解决YOLOv5推理rtsp有延迟的一些方法
sqlalchemy的两种方法详解
软件过程与管理复习(九)
【语音识别入门】基础概念与框架
Judging prime
回顾我的第一份工作求职之旅
MySQL学习笔记(4)——(基本CRUD)操作数据库中的表的数据
10.数据仓库搭建之DWD层搭建
4. Neusoft cross border e-commerce data warehouse project - user behavior data acquisition channel construction of data acquisition channel construction (2022.6.1-2022.6.4)
JNI实用笔记
关于线程池中终止任务
List and map
Solve idea new module prompt module XXXX does exits
Macro definition of C language
Use Flink SQL to transfer market data 1: transfer VWAP
10. DWD layer construction of data warehouse construction