Android multi-threaded services that can be repeatedly started and stopped

In order to avoid deadlocks in a multi-threaded environment, open calls are generally advocated. Open calls can avoid deadlocks at the cost of losing atomicity. But sometimes it will appear logical error, for example:

E.g

 

class A{

  private boolean mIsStarted;
  void start(){
     boolean changed = false;
     synchronized(this){
    if(!mIsStarted){
       mIsStarted = true;
       changed = false;
     }
     if(changed){
       callBack.onStart();
     }
    }
  }

boolean isStarted(){
  sychronized(this){
    return mIstarted;
  }
}
 void stop(){
   boolean changed = false;
   synchronized(this){

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

  if(changed){
    callBack.onStop();
   }
  }
}

  There is nothing wrong with this code in a single-threaded environment. But in a multi-threaded environment there will be a strange phenomenon.

  In principle, onStart must go before 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;
     }

   线程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 comes again, why is the stop method not allowed to be called before start? If a class cannot be restarted, then stop can be before start, otherwise it cannot be before start.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326309308&siteId=291194637