SoFunction
Updated on 2025-04-06

Android multi-threading implements repeated start and stop services

Android multi-threading implements repeated start and stop services

In order to avoid deadlocks in a multi-threaded environment, it is generally recommended to open calls. Open calls can avoid deadlocks, and its price is to lose atomicity. But sometimes it seems logically wrong.

For example:


class A{ 
 
 private boolean mIsStarted; 
 void start(){ 
   boolean changed = false; 
   synchronized(this){ 
  if(!mIsStarted){ 
    mIsStarted = true; 
    changed = false; 
   } 
   if(changed){ 
    (); 
   } 
  } 
 } 
 
boolean isStarted(){ 
 sychronized(this){ 
  return mIstarted; 
 } 
} 
 void stop(){  
  boolean changed = false;  
  synchronized(this){  
 
  if(mStarted){  
   mStarted = false;  
  changed = true;  
  }  
 }  
 
 if(changed){ 
  ();  
  }  
 }  
} 

There is no problem with this code in a single threaded environment. However, strange phenomena will occur in multi-threaded environments.

In principle, onStart must be ahead of onStop, but this is not the case:

The execution steps are as follows:

Thread 1 start

Thread 2 stop

Thread 1

 if(!mIsStarted){

 mIsStarted = true; 
 changed = false; 
} 

Thread 2

synchronized(this){ 

 if(mStarted){  
  mStarted = false;  
 changed = true;  
 }  
}  

Thread 2 onStop

Thread 1 onStart

Now onStop is ahead of onStart. So the question is, how can we ensure that onStart must be in front of onStop?

Then the question is again, why is the stop method not allowed to be called before start? If a class cannot restart, then stop can be before start, otherwise it cannot be before start.

The above is an explanation of the Android multi-threaded service that implements repeated start and stop. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!