当前位置:网站首页>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 .
边栏推荐
- wpa_cli参数说明
- 【建议收藏】消息队列常见的使用场景
- Shell script explanation (II) -- conditional test, if statement and case branch statement
- Is flush easy to use? Is it safe to open a mobile account?
- 每天5分钟玩转Kubernetes | Dashboard典型使用场景
- 如何在 FlowUs和Notion 等笔记软件中进行任务管理?
- wpa_ State machine migration of supplicant
- 贪心之分配问题(1)
- 下拉刷新及上拉加载更多的ListView
- 同花顺难开户么?网上开户安全么?
猜你喜欢

Cookie encryption 3+rpc solution

智能家居不知如何选?不妨看下这篇选购指南

第八届 GopherChina 大会蓄势待发!

vs code突然无法进行代码跳转

C sqlsugar, hisql, FreeSQL ORM framework omni-directional performance test comparison sqlserver
Getting started with database connection pooling (c3p0, Druid)

数字赋能机械制造业,供应链协同管理系统解决方案助力企业供应链再升级

shell脚本详解(七)——正则表达式、sort、uniq、tr

IPLOOK 成为 RedHat(红帽)业务合作伙伴

牛客网:合并区间
随机推荐
In the first half of the year, there were 7 new unicorns in this field, and the capital scrambled to enter the market
chrome突然无法复制粘贴了
函数的导数与微分的关系
牛客网:合并区间
Complete the sqlsession interface and implementation classes
牛客网:判断是否为回文字符串
Paopao Mart: empty souls need stories
回文数(简单版)
加工制造业智慧采购系统解决方案:助力企业实现全流程采购一体化协同
session机制详解以及session的相关应用
2022 t elevator repair recurrent training question bank and answers
jniLibs. Srcdirs = ['LIBS'] what's the use?
如何在 FlowUs和Notion 等笔记软件中进行任务管理?
Niuke network: minimum coverage substring
Custom database connection pool class: requirement: enclose the collection class of a collection object
基于云架构的业务稳定性建设思路
2022 R2 mobile pressure vessel filling test question simulation test platform operation
Iplook 5gc successfully connected with CICA international CHF (billing function)
第八届 GopherChina 大会蓄势待发!
C sqlsugar, hisql, FreeSQL ORM framework omni-directional performance test comparison sqlserver