当前位置:网站首页>Do you use thread or service?
Do you use thread or service?
2022-06-22 19:26:00 【Liuyichu】
In the last article we said Threa and Service It doesn't matter . It basically explains their differences , But the depth is not enough , In this article, we continue to discuss thread and Service!
Let's talk about it first. Thread and Service Some of the differences :
Thread:Thread ( Threads ) Is the smallest unit of program execution , It can be used Thread To perform some asynchronous operations .
Thread The operation of is independent . When one Activity By finish after , If there is no active stop Thread perhaps Thread Inside run If the method is not finished ,Thread And it's going to be carried out all the time . So there's a problem here : When Activity By finish after , No longer hold the Thread References to , And you can no longer control the Thread. On the other hand , There is no way in different Activity Center to same Thread Control .
Service:Service yes android A mechanism of , When it's running, if it's Local Service, So the corresponding Service Is running on the main thread of the main process . If it is Remote Service, So the corresponding Service It runs on the main thread of an independent process .( We talked about that in the last post RemoteService Of )
for example : If One Thread You need to connect to the server at regular intervals to verify the data , The Thread It needs to be running all the time in the background . At this time, if you create this Thread Of Activity It's over and it's time Thread Didn't stop , Then there will be no way to control the Thread, Unless you kill the process of the program . At this point, if you create and start a Service , stay Service It creates 、 Run and control the Thread, This solves the problem ( Because of anything Activity Can be bound to the same Service, And the system will only create a corresponding Service Example ).
So we can Service Think of it as a messaging service , Can be anywhere there is Context Local call to startService or bindService To control it , It can also be in Service Registered in the BroadcastReceiver, By sending broadcast To achieve the purpose of control , These are all Thread Impossible .
Look again. Service Several characteristics of :
(1) By default ,Service Is running in the main thread , If you need to perform complex and time-consuming operations , Must be in Service Create another Thread To perform the task , To avoid ANR.
(2) Service Priority of is higher than that of Activity. Of course , Also higher than in Activity Created in Thread. therefore , The system may give priority to killing the background when the memory is insufficient Activity perhaps Thread, And will not easily kill Service Components , Even if forced to kill Service, It will also restart the killed when resources are available Service.
Actually ,Service and Thread It is not a level thing at all ,Service Is one of the four components of the system . and Thread It is just a tool class used to perform background tasks , It can be Activity Is created in , It can also be in Service Is created in .
therefore , The root of this problem should be , We should not discuss the use of Service still Thread, Instead, we should discuss Where to create Thread?
Typical applications , It can be created in three places , Different locations , Its life cycle is different , therefore , We should be According to the Thread The target life cycle is determined in Service Created in Thread Still Activity Create it in .
(1) stay Activity Is created in
Generally in onCreate Created on , stay onDestroy() Medium destruction , otherwise ,Activity After destruction ,Thread Will still be running in the background .
In this case ,Thread The life cycle of is the whole Activity Life cycle of . therefore , stay Activity Created in the Thread Only suitable for completing some dependencies Activity Tasks related to itself , For example, update regularly Activity Control status, etc .
Core features : The Thread That's why Activity Service , Complete this particular Activity The task assigned , Take the initiative to inform the Activity Some news and events ,Activity After destruction , The Thread There's no point in living .
(2) stay Application Is created in
General customization Application class , heavy load onCreate Method , And create Thread, Of course , Will also be in onTerminate() Method of destruction Thread, otherwise , If Thread If you don't quit , Even if the whole Application Out of the ,Thread Still running in the background .
In this case ,Thread The life cycle of is the whole Application Life cycle of . therefore , stay Application Created in the Thread, It can perform some tasks at the whole application level , For example, regularly check the network connection status and so on .
Core features : The Thread The ultimate goal is for this APP Each of them Activity Service , Including completing a Activity The task assigned , Take the initiative to inform someone Activity Some news and events, etc ,APP After exiting, you should Thread There's no point in living .
In both cases ,Thread The life cycle of should not exceed the entire application life cycle , That is to say , Whole APP After you quit ,Thread Should quit completely , So there won't be memory leaks or zombie threads . that , If you want the whole APP Can still run this after exiting Thread, Then we should put Thread Put it in Service To create and launch .
(3) stay Service Is created in
This is to guarantee the longest life cycle Thread The only way , As long as the whole Service Do not exit ,Thread It can be executed in the background all the time , Generally in Service Of onCreate() Created in , stay onDestroy() Medium destruction .
therefore , stay Service Created in the Thread, Suitable for long-term execution some independent of APP Background tasks for , The common one is : stay Service Keep a long connection with the server side .
Core features : The Thread It can be for APP Provide some “ service ” perhaps “ State query ”, But it's time to Thread There is no need to take the initiative to inform APP Any incident , You don't even need to know APP Who is it? .
All in all , We're not thinking about using Thread Or should I use it Service, It should be for Thread Choose the right life cycle , This is my right to Service and Thread Thinking and understanding .
边栏推荐
- jniLibs.srcDirs = [‘libs‘]有什么用?
- IPLOOK 5GC与亚信国际CHF(计费功能)对接成功
- 2022 R2 mobile pressure vessel filling test question simulation test platform operation
- shell脚本(五)——函数
- Niuke.com: judge whether it is palindrome string
- 牛客网:合并区间
- Makefile将某一部分文件不编译
- jniLibs. Srcdirs = ['LIBS'] what's the use?
- Chrome suddenly can't copy and paste
- PostgreSQL 字符串分隔函数(regexp_split_to_table)介绍以及示例应用
猜你喜欢

每天5分钟玩转Kubernetes | Dashboard典型使用场景

Typescript (7) generic

RobotFramework 安装教程
DBMS in Oracle_ output. put_ Example of line usage

Flutter系列-flutter路由管理

2022 G2 power plant boiler stoker question bank and online simulation examination

集群、分布式、微服务概念和区别

链表4- 21 合并两个有序链表

Niuke network: minimum coverage substring

Robotframework installation tutorial
随机推荐
有效的括号
wpa_cli参数说明
Sre is bound to move towards the era of chaotic engineering -- Huawei cloud chaotic engineering practice
Flush difficult to open an account? Is it safe to open an account online?
Active directory user logon Report
Niuke network: minimum coverage substring
贪心之区间问题(3)
Postman learning
Paopao Mart: empty souls need stories
DBMS in Oracle_ output. put_ Example of line usage
机械设备行业数字化供应链集采平台解决方案:优化资源配置,实现降本增效
牛客网:最小覆盖子串
集群、分布式、微服务概念和区别
Flutter系列-搭建Flutter开发环境
Exness sorted out three problems to be solved in Musk's acquisition of Twitter
Is flush easy to open an account? Is it safe to open a mobile account?
20billion vs 5billion, how much is the "dehydration" little red book worth?
Getting started with database connection pooling (c3p0, Druid)
贪心之区间问题(1)
Pre training language model, Bert, roformer SIM, also known as simbertv2