当前位置:网站首页>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 .
边栏推荐
- 解决idea新建module 提示module xxxx does exitst
- 【Bug解决】org.apache.ibatis.type.TypeException: The alias ‘xxxx‘ is already mapped to the value ‘xxx‘
- ES6 adds -let and const (disadvantages of VaR & let and const)
- 回顾我的第一份工作求职之旅
- pymongo模糊查询
- 10. DWD layer construction of data warehouse construction
- E-commerce user behavior real-time analysis system (flink1.10.1)
- Page navigation of wechat applet
- 5.1数据采集通道搭建之业务数据采集通道搭建
- Bottomsheetdialogfragment imitation Tiktok comment box
猜你喜欢
随机推荐
5.1数据采集通道搭建之业务数据采集通道搭建
Scala初级实践——统计手机耗费流量(1)
9. Dim layer construction of data warehouse construction
Application of recursion
6. Data warehouse design for data warehouse construction
2.东软跨境电商数仓项目技术选型
安卓实现真正安全的退出app
东软跨境电商数仓开发进度
Paddle的OCR标签转化为TXT格式
kotlin作用域函数
正则替换group(n)内容
MySQL学习笔记(5)——JOIN联表查询,自连接查询,分页和排序,子查询与嵌套查询
Preorder, middle order and postorder traversal of binary tree
微信小程序密码显示隐藏(小眼睛)
关于Kotlin泛型遇到的问题
Could not locate zlibwapi.dll. Please make sure it is in your library path
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)
MySQL学习笔记(4)——(基本CRUD)操作数据库中的表的数据
[first launch in the whole network] will an abnormal main thread cause the JVM to exit?
List and map









