我应该使用什么同步方法来暂停消费者队列线程?

发布于 2024-11-01 07:02:56 字数 210 浏览 1 评论 0原文

我有一个带有 LinkedBlockingQueue 的 Android 应用程序,我用它在单独的线程(称为网络线程)上运行一系列网络作业。当我从网络作业返回特定响应时,我需要暂停作业以便从对话框中进行用户输入。我想阻塞网络线程,直到用户输入完成,然后解除阻塞,以便它可以继续处理网络作业。哪种并发机制在这里最有意义?

编辑: 由于暂停是根据网络作业的结果执行的,因此暂停事件来自网络线程,

I have an Android application with a LinkedBlockingQueue that I'm using to run a series of 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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情深已缘浅 2024-11-08 07:02:56

编辑:
您的编辑使解决方案变得更容易一些。您仍然需要信号发送,但您可以解决我放入的复杂混乱。您可以使用简单的 ReentrantLock 和标志。

也许是这样的

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(); 
      }

}

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(); 
      }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文