【问题标题】:Java Semaphore Thread Based Permit基于 Java 信号量线程的许可
【发布时间】:2021-06-05 16:34:06
【问题描述】:

我想用Semaphore 阻塞线程(或替代)。但是同一个线程不应该获得多个许可。例如:

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);
    }

}

输出是:

3
2
1
testSync finished
0
1
--just waiting

--just waiting 行继续使用信号量,如synchronized

【问题讨论】:

  • 你想达到什么目的?
  • "但同一个线程不应获得多个许可。" - 假设一个线程第二次为您的自定义信号量调用.acquire()方法,您想要实现什么行为?是否应该只返回一个方法而不更新信号量的计数器?对于问题帖子中的单线程代码,不清楚您为什么要使用信号量或其他同步机制:这些机制仅在多线程程序中有用。
  • 方法在调用.release() 方法之前不应增加信号量的计数器。例如,您试图阻止每个线程的多个数据库连接。

标签: java concurrency semaphore


【解决方案1】:

我猜你想要ReentrantLock,但这只是一个猜测,因为问题有点不清楚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2012-04-05
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多