当前位置:网站首页>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 .
边栏推荐
- Protection strategy of server area based on Firewall
- 2. Heap sort "hard to understand sort"
- 从 1.5 开始搭建一个微服务框架链路追踪 traceId
- Zhiting doesn't use home assistant to connect Xiaomi smart home to homekit
- JSON parsing instance (QT including source code)
- 【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
- [deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
- Wechat applet 01
- Promoted to P8 successfully in the first half of the year, and bought a villa!
- Why do we use UTF-8 encoding?
猜你喜欢
![[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering](/img/a4/7320f5d266308f6003cc27964e49f3.png)
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering

CTFshow,信息搜集:web5

Guangzhou Development Zone enables geographical indication products to help rural revitalization

【兰州大学】考研初试复试资料分享

Promoted to P8 successfully in the first half of the year, and bought a villa!

Ctfshow, information collection: web6

CTFshow,信息搜集:web14

【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类

从 1.5 开始搭建一个微服务框架链路追踪 traceId

【深度学习】图像超分实验:SRCNN/FSRCNN
随机推荐
一个需求温习到的所有知识,h5的表单被键盘遮挡,事件代理,事件委托
Use cpolar to build a business website (2)
[data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering
Ctfshow, information collection: web5
Used by Jetson AgX Orin canfd
CTFshow,信息搜集:web9
PG basics -- Logical Structure Management (locking mechanism -- table lock)
Bye, Dachang! I'm going to the factory today
什麼是數據泄露
Ctfshow, information collection: web4
JSON parsing instance (QT including source code)
Niuke real problem programming - day13
Niuke real problem programming - day15
Window环境下配置Mongodb数据库
微信小程序 01
STM32F103C8T6 PWM驱动舵机(SG90)
[follow Jiangke University STM32] stm32f103c8t6_ PWM controlled DC motor_ code
Niuke real problem programming - day18
Promoted to P8 successfully in the first half of the year, and bought a villa!
CTFshow,信息搜集:web10