簡體   English   中英

Java 基於信號量線程的許可證

[英]Java Semaphore Thread Based Permit

我想用Semaphore (or alternative)阻塞線程。 但是同一個線程不應該獲得多個許可。 例如:

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 是:

3
2
1
testSync finished
0
1
--just waiting

是否有任何 Semaphore 的替代方案可以繼續在--just waiting row like synchronized

我猜你想要一個ReentrantLock ,但這只是一個猜測,因為問題有點不清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM