Multithreading 限制调用()内的并发方法执行

Multithreading 限制调用()内的并发方法执行,multithreading,callable,Multithreading,Callable,我的代码中有一个call()方法,它根据特定的条件调用特定的方法: call(){ if(a){ methodA(); } if(b){ methodB(); } if(c){ methodC(); } } 在上面的场景中,我想限制methodC的并发执行。 如何实现这一点?这里您需要的是一个构造(检查示例中的保镖/夜总会规范) 如果要将并发执行的数量限制为一次最多一个,则应使用锁。在Java中,它应该如下所示: final L

我的代码中有一个call()方法,它根据特定的条件调用特定的方法:

call(){
  if(a){
      methodA(); 
  }
  if(b){
      methodB(); 
  }
  if(c){
      methodC(); 
  }
}
在上面的场景中,我想限制methodC的并发执行。 如何实现这一点?

这里您需要的是一个构造(检查示例中的保镖/夜总会规范)


如果要将并发执行的数量限制为一次最多一个,则应使用
锁。在Java中,它应该如下所示:

final Lock lock = new ReentrantLock();
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      lock.lock();
      try {
         methodC(); 
      } finally {
         lock.unlock();
      }
  }
}

如果要将并发执行的数量限制为一次执行多个,可以使用
信号量
;这里,允许的并发调用是一个int

final Semaphore semaphore = new Semaphore(CONCURRENT_CALLS_ALLOWED);
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      semaphore.aquire();//throws checked exception
      try {
         methodC(); 
      } finally {
         semaphore.release();
      }
  }
}

你能更具体一点你所说的“限制”是什么意思吗?假设多个线程(例如10个线程)正在调用call()方法,并且对于所有线程,如果(c)返回true,那么在某个时间,只有特定数量的线程(例如3个)应该同时执行methodC。其他线程将在这3个线程完成任务后执行。因此,将methodC的并发执行限制为3
final Semaphore semaphore = new Semaphore(CONCURRENT_CALLS_ALLOWED);
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      semaphore.aquire();//throws checked exception
      try {
         methodC(); 
      } finally {
         semaphore.release();
      }
  }
}