限制 call() 内的并发方法执行
Limit concurrent method executions inside call()
我的代码中有一个 call() 方法,它会根据特定条件调用特定方法:
call(){
if(a){
methodA();
}
if(b){
methodB();
}
if(c){
methodC();
}
}
在上面的场景中,我想限制方法C的并发执行。
如何实现?
这里您需要的是 Semaphore 构造(检查示例中的 bouncer/night 俱乐部规范)。
// Create the semaphore with 3 slots, where 3 are available.
var bouncer = new Semaphore(3, 3);
call(){
if(a){
methodA();
}
if(b){
methodB();
}
if(c){
// Let a thread execute only after acquiring access (a semaphore to be released).
Bouncer.WaitOne();
methodC();
// This thread is done. Let someone else go for it
Bouncer.Release(1);
}
}
如果您想将并发执行的数量限制为一次最多一个,那么您应该使用 Lock
。在 Java 中它应该看起来像:
final Lock lock = new ReentrantLock();
call() {
if(a) {
methodA();
}
if(b) {
methodB();
}
if(c) {
lock.lock();
try {
methodC();
} finally {
lock.unlock();
}
}
}
如果你想限制一次并发执行的数量超过一个,你可以使用一个Semaphore
;这里 CONCURRENT_CALLS_ALLOWED 是一个整数。
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();
}
}
}
我的代码中有一个 call() 方法,它会根据特定条件调用特定方法:
call(){
if(a){
methodA();
}
if(b){
methodB();
}
if(c){
methodC();
}
}
在上面的场景中,我想限制方法C的并发执行。 如何实现?
这里您需要的是 Semaphore 构造(检查示例中的 bouncer/night 俱乐部规范)。
// Create the semaphore with 3 slots, where 3 are available.
var bouncer = new Semaphore(3, 3);
call(){
if(a){
methodA();
}
if(b){
methodB();
}
if(c){
// Let a thread execute only after acquiring access (a semaphore to be released).
Bouncer.WaitOne();
methodC();
// This thread is done. Let someone else go for it
Bouncer.Release(1);
}
}
如果您想将并发执行的数量限制为一次最多一个,那么您应该使用 Lock
。在 Java 中它应该看起来像:
final Lock lock = new ReentrantLock();
call() {
if(a) {
methodA();
}
if(b) {
methodB();
}
if(c) {
lock.lock();
try {
methodC();
} finally {
lock.unlock();
}
}
}
如果你想限制一次并发执行的数量超过一个,你可以使用一个Semaphore
;这里 CONCURRENT_CALLS_ALLOWED 是一个整数。
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();
}
}
}