简体   繁体   English

Java 基于信号量线程的许可证

[英]Java Semaphore Thread Based Permit

I want to block threads with Semaphore (or alternative) .我想用Semaphore (or alternative)阻塞线程。 But same thread should not acquire multiple permit.但是同一个线程不应该获得多个许可。 For example:例如:

import java.util.concurrent.Semaphore;

public class ConcurencyTest {

    public static void main(String[] args) throws InterruptedException {
        new ConcurencyTest().testSync(3);
        System.out.println("testSync finished");
        new ConcurencyTest().testSemaphore();
        System.out.println("testSemaphore finished");
    }

    public void testSemaphore() throws InterruptedException {
        final Semaphore s = new Semaphore(2);
        for (int i = 0; i < 10; i++) {
            s.acquire();
            System.out.println(i);
        }
    }

    public synchronized void testSync(int i) {
        if (i == 0) return;
        System.out.println(i);
        testSync(i - 1);
    }

}

Output is: Output 是:

3
2
1
testSync finished
0
1
--just waiting

Is there any alternative of Semaphore for continue at --just waiting row like synchronized .是否有任何 Semaphore 的替代方案可以继续在--just waiting row like synchronized

I guess you want a ReentrantLock , but that is just a guess since the question is bit unclear.我猜你想要一个ReentrantLock ,但这只是一个猜测,因为问题有点不清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM