코드 사본은 다음과 같습니다.
패키지 com.yao;
import java.util.concurrent.executorservice;
java.util.concurrent.executors import;
java.util.concurrent.semaphore import;
/**
* 4 개의 새로운 동기화 장치를 조정하기위한 새로운 동기화 장치는 Java 5.0에 추가됩니다.
* 세마포어, CountdownLatch, Cyclicbarrier 및 교환기.
*이 예제는 주로 세마포어를 소개합니다.
* 세마포어는 자원 풀을 관리하는 데 사용되는 도구로, 패스로 간주 될 수 있습니다.
* 스레드가 리소스 풀에서 리소스를 얻으려면 먼저 패스를 얻어야합니다.
* 스레드가 패스를 일시적으로 얻을 수 없으면 스레드가 차단되어 대기 상태로 들어갑니다.
*/
공개 클래스 MySemaphore 확장 스레드 {
개인 INT I;
개인 세마포어 세마포어;
공개 mysemaphore (int i, semaphore semaphore) {
this.i = i;
this.semaphore = 세마포어;
}
public void run () {
if (semaphore.availablePermits ()> 0) {
System.out.println ( ""+i+"사용 가능한 공백이 있습니다 :");
}또 다른{
System.out.println ( ""+i+"대기, 공간 없음");
}
노력하다 {
semaphore.acquire ();
} catch (InterruptedException e) {
e.printstacktrace ();
}
System.out.println ( ""+i+"빈 공간 가져 오기");
노력하다 {
Thread.sleep ((int) math.random ()*10000);
} catch (InterruptedException e) {
e.printstacktrace ();
}
System.out.println ( ""+i+"완전히 사용");
semaphore.release ();
}
public static void main (String [] args) {
세마포어 세마포어 = 새로운 세마포어 (2);
ExecutorService Service = Executor.NewCachedThreadPool ();
for (int i = 0; i <10; i ++) {
Service.Execute (New MySemaphore (I, Semaphore));
}
service.shutdown ();
semaphore.acquireuninterrupruply (2);
System.out.println ( "사용, 청소가 필요합니다");
semaphore.release (2);
}
}