开发者

What synchronization method should I use for pausing a consumer queue thread?

开发者 https://www.devze.com 2023-02-24 02:04 出处:网络
I have an Android application with a LinkedBlockingQueue that I\'m using to run a series of开发者_Go百科 network jobs on a separate thread (call it the network thread).When I get back a certain respon

I have an Android application with a LinkedBlockingQueue that I'm using to run a series of开发者_Go百科 network jobs on a separate thread (call it the network thread). When I get back a certain response from a network job I need to pause the jobs for user input from a dialog. I'd like to block the network thread until the user input is complete, and then unblock it so that it can continue to process the network jobs. What concurrency mechanism makes the most sense here?

EDIT: Since the pausing is performed based on the results of a network job, the pausing event comes from the network thread,


Edit: Your edit makes the resolution a bit easier. You would still need signaling but you can scratch the complicated mess I put in. You can use a simple ReentrantLock and a flag.

Maybe something like this

boolean needsToWaitForUserInput = false;
final ReentrantLock lock = new ReentrantLock();
final Condition waitingCondition = lock.newCondition();

private final Runnable networkRunnable=new Runnable(){ 
  public void run(){
      //get network information
      lock.lock();
      needsToWaitForUserInput  = true;
      try{      
         while(needsToWaitForUserInput ){
            waitingCondition.await();
         }
      }finally{ 
          lock.unlock();
      }
   }
}
    public void signalJobToContinue(){
      lock.lock();
      try{      
            needsToWaitForUserInput =false;
            waitingCondition.signal();
      }finally{ 
         lock.unlock(); 
      }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消