当前位置:网站首页>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 .
边栏推荐
猜你喜欢

Niuke real problem programming - day14

Win10 or win11 taskbar, automatically hidden and transparent
MongoD管理数据库的方法介绍
![[server data recovery] data recovery case of raid failure of a Dell server](/img/5d/03bc8dcc6e554273b34a78c49a9eaf.jpg)
[server data recovery] data recovery case of raid failure of a Dell server

暑期安全很重要!应急安全教育走进幼儿园
![[server data recovery] a case of RAID data recovery of a brand StorageWorks server](/img/aa/6d820d97e82df1d908dc7aa78fc8bf.png)
[server data recovery] a case of RAID data recovery of a brand StorageWorks server

Notes HCIA

asp. Netnba information management system VS development SQLSERVER database web structure c programming computer web page source code project detailed design

Ctfshow, information collection: web6

Spatiotemporal deformable convolution for compressed video quality enhancement (STDF)
随机推荐
IDA pro逆向工具寻找socket server的IP和port
PG basics -- Logical Structure Management (locking mechanism -- table lock)
What are PV and UV? pv、uv
Delete a whole page in word
从 1.5 开始搭建一个微服务框架链路追踪 traceId
广州开发区让地理标志产品助力乡村振兴
Window环境下配置Mongodb数据库
Unity's ASE realizes cartoon flame
"Baidu Cup" CTF competition 2017 February, web:include
What is data leakage
知否|两大风控最重要指标与客群好坏的关系分析
居然从408改考自命题!211华北电力大学(北京)
CTFshow,信息搜集:web7
jacoco代码覆盖率
Niuke real problem programming - day16
【搞船日记】【Shapr3D的STL格式转Gcode】
【数据挖掘】视觉模式挖掘:Hog特征+余弦相似度/k-means聚类
CTFshow,信息搜集:web10
【数字IC验证快速入门】25、SystemVerilog项目实践之AHB-SRAMC(5)(AHB 重点回顾,要点提炼)
Bits and Information & integer notes