当前位置:网站首页>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 .
边栏推荐
- Andriod --- JetPack :LiveData setValue 和 postValue 的区别
- Briefly describe the working principle of kept
- Integer learning
- Deformable convolutional dense network for enhancing compressed video quality
- Window环境下配置Mongodb数据库
- “百度杯”CTF比赛 2017 二月场,Web:include
- Ctfshow, information collection: web12
- Implementation of crawling web pages and saving them to MySQL using the scrapy framework
- Niuke real problem programming - Day12
- Ctfshow, information collection: web9
猜你喜欢

MySQL bit类型解析

Niuke real problem programming - day16

Unity's ASE achieves full screen sand blowing effect

Notes HCIA

8大模块、40个思维模型,打破思维桎梏,满足你工作不同阶段、场景的思维需求,赶紧收藏慢慢学

Summer safety is very important! Emergency safety education enters kindergarten

2. Heap sort "hard to understand sort"

什么是数据泄露
![[make a boat diary] [shapr3d STL format to gcode]](/img/aa/6113c51ca82b00c0adc42fbf3f2b4b.png)
[make a boat diary] [shapr3d STL format to gcode]
![[target detection] yolov5 Runtong voc2007 data set](/img/b3/b7f3d46075cb1782d772a24362003e.png)
[target detection] yolov5 Runtong voc2007 data set
随机推荐
MySQL bit type resolution
【數據挖掘】視覺模式挖掘:Hog特征+餘弦相似度/k-means聚類
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)
TypeScript 发布 4.8 beta 版本
PAT 甲级 1103 Integer Factorizatio
Niuke real problem programming - Day12
[机缘参悟-40]:方向、规则、选择、努力、公平、认知、能力、行动,读3GPP 6G白皮书的五层感悟
Stream learning notes
Compile advanced notes
A need to review all the knowledge, H5 form is blocked by the keyboard, event agent, event delegation
MongoD管理数据库的方法介绍
MySQL bit类型解析
Ctfshow, information collection: web4
[server data recovery] a case of RAID data recovery of a brand StorageWorks server
Ctfshow, information collection: web10
What is data leakage
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
【搞船日记】【Shapr3D的STL格式转Gcode】
【OBS】RTMPSockBuf_Fill, remote host closed connection.
[understanding of opportunity -40]: direction, rules, choice, effort, fairness, cognition, ability, action, read the five layers of perception of 3GPP 6G white paper