라지 쿠마르 Natarajan를 :
나는 자바에서 뮤텍스와 세마포어에 대해 배우고 있습니다. 그래서 난 내 손 더러워지고 생각했다.
그 뮤텍스이에서 하나의 허가와 세마포어 이해 링크 와 뮤텍스이에서 소유권의 개념이 링크를 .
소유권을 증명하기 위해 나는 프로그램 아래 작성 및 출력 아래에서 발견했다. 내가 획득보다 더 출시 할 때, 실제로 허가의 수를 증가시킨다.
아래는 프로그램입니다.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
public class MutexOwnerShipDemo {
public static void main(String[] args) {
Semaphore mutex = new Semaphore(1);
final ExecutorService es = Executors.newSingleThreadExecutor();
try {
// acquire mutex lock permit in main thread
mutex.acquire();
// release the lock in different thread
Future mutexWait = es.submit(() -> mutex.release());
mutexWait.get();
System.out.println("mutexWait.isDone() " + mutexWait.isDone() );
System.out.println("successfully released permits for mutex \n " +
"available permits are " + mutex.availablePermits());
// release the lock in main thread
mutex.release();
System.out.println( "available permits are " + mutex.availablePermits());
// release lock in main thread once again
mutex.release();
System.out.println( "available permits are " + mutex.availablePermits());
} catch (Exception e) {
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> es.shutdownNow()));
System.out.println(es.isShutdown());
}
}
출력은 -
mutexWait.isDone() true
successfully released permits for mutex
available permits are 1
available permits are 2
available permits are 3
false
예상이 동작입니다. 그래서, 어떻게 작동하는 경우
내 자바 설치 세부 사항 -
$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
앤드류 Tobilko :
네,에 인용 된 예상되는 동작입니다 문서는 :
[...]은 하나 허용 가능한 수를 증가 허가를 해제. [...] 스레드 놓을은 허가를 호출하여 그 허가를 획득해야한다는 요구 사항은 없습니다
acquire()
.
당신은 당신이 원하는대로 많은 허락 해제 할 수 있습니다 :
Semaphore semaphore = new Semaphore(0);
semaphore.release(10); // it's fine
System.out.println(semaphore.availablePermits()); // 10
당신은 허가의 난수 (정확하게, 이용 가능한 허가 (permit)의 현재 수를 초과하는 수)하지만를 얻을 수 없습니다 :
Semaphore semaphore = new Semaphore(0);
semaphore.acquire(10); // you are blocked here
Semaphore semaphore = new Semaphore(0);
System.out.println(semaphore.tryAcquire(10)); // false