我正在编写一个测试代码,我发现如果我们在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();
}
}
}
有人可以解释这种行为吗?