当前位置:网站首页>Whether runnable can be interrupted
Whether runnable can be interrupted
2022-07-07 15:20:00 【I am not diligent V】
background : The landlord encountered a problem in the project development , stay Activity You need to start a sub thread to perform time-consuming tasks ,Activity sign out onDestroy after , Release resources . Just when the sub thread is performing time-consuming tasks, it needs to access the released resources , Then a null pointer exception crash occurred .
reason : Main thread and sub thread are concurrent , The main thread Activity When to exit to release resources , When does a child thread access resources , The timing of the two is uncontrollable .
1) Is it OK to lock it ?
The main thread Activity sign out Lock when releasing resources ,; Sub thread execution Runnable Time lock , And the sub thread determines whether the resource has been released before executing the task .
This may lead to ANR problem : In case the sub thread takes a long time , Main thread exit Activity Because the lock is held by the sub thread, it has been waiting , Yes ANR risk .
2) No locks , Use volatile Keyword marks whether to release variables
Main thread exit Activity when ,volatile Variable Set to true The representative has been released . Zi Xiancheng runnable Judge before execution volatile The value of the variable , If true Represents whether the resource , No more execution .
There are still sporadic crashes reported after the launch : Zi Xiancheng runnable Judge volatile Variable time , Resources haven't been released yet . Perform subsequent logic , Resources are released, causing a crash .
sequential : Subthread judgment volatile Variable , adopt —— The main thread releases resources —— The subsequent logical access resources of the sub thread
So the landlord thought , Main thread exit Activity when , Resources used in the life cycle should be released , Including sub threads Runnable, Give Way Runnable Do not execute or interrupt .—— But can it really be interrupted ?
- Some people say Handler Of removeCallbacksAndMessages—— For unexecuted Runnable, Sure , But for those who have already run Runnable, no way .
- Some people say Thread.interrupt, however interrupt It only notifies the stopped thread , In fact, for the stopped thread , It has full autonomy , It can either choose to stop immediately , You can also choose to stop after a period of time , You can also choose not to stop at all .—— This is Java No forced thread stop mechanism is provided .
- Some people say that thread pool shutdownNow Method , however shtdownNow The essence of the method is also to send to the executing thread interrupt.
- Some people say that using thread pool Submit(Runnable runnable) Return to one Future, Finally through Future Of cancel The method is not enough ??—— Landlord's personal test , Running Runnable Not yet. .
Try the above , Use as follows Demo verification , Activity Destroy after ,Runnable Still carry out ......
public class TestActivity extends Activity {
private Runnable runnable;
private HandlerThread handlerThread;
private Handler handler;
private Thread thread;
private Future future;
private ExecutorService executorService;
private Handler mainHandler = new Handler(Looper.getMainLooper());
public static void startActivity(Context context) {
Intent intent = new Intent(context, TestActivity.class);
context.startActivity(intent);
}
private void init() {
runnable = new Runnable() {
@Override
public void run() {
while (true) {
try{
Thread.sleep(1000);
Log.e("testing", "runnable run...." + TestActivity.this);
} catch (Exception e) {
Log.e("testing", "e run...." + e.toString());
}
}
}
};
//1. handlerThread
// handlerThread = new HandlerThread("test-handler-thread");
// handlerThread.start();
// handler = new Handler(handlerThread.getLooper());
// handler.post(runnable);
//2. Thread
// thread = new Thread(runnable);
// thread.start();
//3. future
executorService = Executors.newSingleThreadExecutor();
future = executorService.submit(runnable);
}
private void release() {
//1.handlerThread
// handlerThread.quit();
// handler.removeCallbacks(runnable);
//2. Thread
// try {
// thread.interrupt();
// } catch (Exception e) {
// }
//3. future
if(future != null) {
boolean ret = future.cancel(true);
executorService.shutdown();
Log.e("testing", "future cancel...." + ret);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
Log.e("testing", "act onCreate ");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
init();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TestActivity.this.finish();
}
});
}
@Override
protected void onDestroy() {
release();
Log.e("testing", "act onDestroy ");
super.onDestroy();
}
}
actually ,JAVA Recommended the use of Thread.currentThread().isInterrupted() Method to determine whether the thread is interrupted
That is to say Demo in Runnable Of while(true) It is amended as follows while(!Thread.currentThread().isInterrupted())
Just Demo for , Interrupt can be implemented Runnable, But the actual project Runnable Not all the time , Mostly a time-consuming task . Thread.currentThread().isInterrupted() Judgment cannot run through the whole Runnable, It can only be called at a certain time —— In case of Runnable Call inside isInterrupted() When the thread is not interrupt, call isInterrupted() After judgment, the thread interrupt, runnable Still access the released resources .
边栏推荐
- "Baidu Cup" CTF competition 2017 February, web:include
- 众昂矿业:萤石继续引领新能源市场增长
- How to enable radius two factor / two factor (2fa) identity authentication for Anheng fortress machine
- 【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
- 一个需求温习到的所有知识,h5的表单被键盘遮挡,事件代理,事件委托
- HW初级流量监控,到底该怎么做
- Ctfshow, information collection: web8
- Win10 or win11 taskbar, automatically hidden and transparent
- 2. Heap sort "hard to understand sort"
- What are the safest securities trading apps
猜你喜欢
居然从408改考自命题!211华北电力大学(北京)
8大模块、40个思维模型,打破思维桎梏,满足你工作不同阶段、场景的思维需求,赶紧收藏慢慢学
【服务器数据恢复】某品牌StorageWorks服务器raid数据恢复案例
【兰州大学】考研初试复试资料分享
asp. Netnba information management system VS development SQLSERVER database web structure c programming computer web page source code project detailed design
从 1.5 开始搭建一个微服务框架链路追踪 traceId
[Data Mining] Visual Pattern Mining: Hog Feature + cosinus Similarity / K - means Clustering
MongoD管理数据库的方法介绍
[server data recovery] a case of RAID data recovery of a brand StorageWorks server
Typescript release 4.8 beta
随机推荐
Connecting FTP server tutorial
[server data recovery] a case of RAID data recovery of a brand StorageWorks server
Niuke real problem programming - Day12
Notes HCIA
Niuke real problem programming - day15
Niuke real problem programming - day16
Ctfshow, information collection: web10
Promoted to P8 successfully in the first half of the year, and bought a villa!
上半年晋升 P8 成功,还买了别墅!
There is a cow, which gives birth to a heifer at the beginning of each year. Each heifer has a heifer at the beginning of each year since the fourth year. Please program how many cows are there in the
CTFshow,信息搜集:web14
Andriod --- JetPack :LiveData setValue 和 postValue 的区别
PAT 甲级 1103 Integer Factorizatio
Bye, Dachang! I'm going to the factory today
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
Niuke real problem programming - Day17
简述keepalived工作原理
[understanding of opportunity -40]: direction, rules, choice, effort, fairness, cognition, ability, action, read the five layers of perception of 3GPP 6G white paper
Implementation of crawling web pages and saving them to MySQL using the scrapy framework
【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)