我正在编写一个测试代码,发现如果将release()放在acquire()之前,则二进制信号量功能已损坏。

我检查并发现,然后有多个线程通过acquire()并将计数增加到N,其中N是线程数,因此与二进制信号量矛盾。

import java.util.concurrent.Semaphore;

/**
 * Consider an ATM cubicle with 1 ATM, Semaphore can make sure only 1 person
 * can access simultaneously.
 *
 * Here if relese() comes before then this binary semaphore is not working.
 */
public class SemaphoreTest {

    // max 4 people
    static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {

        System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

        MyATMThread t1 = new MyATMThread("A",semaphore);
        t1.start();

        MyATMThread t2 = new MyATMThread("B",semaphore);
        t2.start();

        MyATMThread t3 = new MyATMThread("C",semaphore);
        t3.start();

        MyATMThread t4 = new MyATMThread("D",semaphore);
        t4.start();

        MyATMThread t5 = new MyATMThread("E",semaphore);
        t5.start();

        MyATMThread t6 = new MyATMThread("F",semaphore);
        t6.start();

    }
}

class MyATMThread extends Thread {

    String name = "";
    Semaphore semaphore = null;

    MyATMThread(String name,Semaphore s) {
        this.name = name;
        this.semaphore=s;
    }

    public void run() {

        try {

            System.out.println(name + " : acquiring lock...");
            System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());
            semaphore.release();
            semaphore.acquire();
            System.out.println(name + " : got the permit!");

            try {

                for (int i = 1; i <= 5; i++) {

                    System.out.println(name + " : is performing operation " + i + ", available Semaphore permits : "
                            + semaphore.availablePermits());

                    // sleep 1 second
                    Thread.sleep(1000);

                }

            } finally {

                // calling release() after a successful acquire()
                System.out.println(name + " : releasing lock...");
                semaphore.release();
                System.out.println(name + " : available Semaphore permits now: " + semaphore.availablePermits());

            }

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}


有人可以解释这种行为吗?

最佳答案

是的,您正在通过获取之前释放(增加许可)来编写损坏的代码(至少达到您的期望)。这是完全有效的,但是如果您打算获得一个许可证,则不应通过在release()之前调用acquire()来增加它们。

Semaphore允许您将许可增加到超出初始数量的范围。这可以用于例如节流。辅助线程将执行acquire()/release(),而调节器将根据某些逻辑来减少/增加许可。

09-25 20:56