java - 有没有办法在java(或scala)信号量对象中​​包含条件来获取方法?

标签 java scala locking semaphore synchronization

我有一个包含多个线程的程序,以六个线程为例。其中五个线程应该能够同时使用给定的资源,但如果发生给定的条件,最后一个线程不应该同时使用,并且应该等到该条件结束。

根据我的理解,不能使用 ReentrantLock,因为它一次只能由一个线程持有。另一方面,信号量可以同时被多个线程持有,但我找不到将条件附加到获取方法的方法。

这个高级对象可以解决这个问题吗?或者我必须直接使用通知和等待来实现此功能?

例如。

class A{
   getResource{ ... }
}

//This Runable could be spawn many times at the same time
class B implements Runnable{
   run {
      setConditionToTrue
      getResource
      ...
      getResource
      ...
      getResource
      setConditionToFalse
   }
}

//This will be working forever but only one Thread
class C implements Runnable{
   run{
      loop{
         if(Condition == true) wait
         getResource
      }
   }
}

先谢谢各位了

最佳答案

我在这里重申您的问题:您希望 B 线程同时访问共享资源,但 C 线程应该等待某些条件发生才能使用该资源。

如果我正确理解你的问题,你可以使用ReentrantLock来解决你的问题。

引入一个名为getAccess()的新函数,并让C线程调用该函数来获取共享资源。引入另外两个函数来允许和停止对共享资源的访问。

class A {

  private final ReentrantLock lock = new ReentrantLock();
  private Condition someCondition = lock.newCondition();
  private boolean bCondition = false;

  getResource{ ... } // Your existing method used by B threads

  getAccess() { // Protected access to some resource, called by C thread
    lock.acquire();

    try {
      if (!bCondition)
        someCondition.await(); // B thread will wait here but releases the lock
    } finally {
      lock.release();
    }
  }

  allowAccess() { // B thread can call this func to notify C and allow access
    lock.acquire();
    try {
      bCondition = true;
      someCondition.signal(); // Decided to release the resource
    } finally {
      lock.release();
    }
  }

  stopAccess() { // B thread can stop the access
    lock.acquire();
    try {
      bCondition = false;
    } finally {
      lock.release();
    }
  }

}

关于java - 有没有办法在java(或scala)信号量对象中​​包含条件来获取方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166699/

相关文章:

scala - Spark流: Broadcast variables, java.lang.ClassCastException

xml - 来自 Maven 的 Scalatest : How to tag and filter out an entire Suite?

c++ - 判断SQLite数据库是否被锁定

Java 锁定单词,使其无法使用

java - 限制我的方法的执行时间

javascript - 在java中的 Controller 端处理动态生成的表单元素

java - JavaFX 中 StackPane 上的 BufferedImage

algorithm - 以功能方式遍历树

java - 使用我创建的 Exception 类捕获抛出的异常

.net - 线程安全的一次计算最佳实践