การคัดลอกรหัสมีดังนี้:
แพ็คเกจ com.yo;
นำเข้า java.util.concurrent.executorservice;
นำเข้า java.util.concurrent.executors;
นำเข้า java.util.concurrent.semaphore;
-
* 4 อุปกรณ์การซิงโครไนซ์ใหม่สำหรับการประสานงานกระบวนการระหว่างเธรดจะถูกเพิ่มใน Java 5.0 ซึ่งก็คือ:
* Semaphore, Countdownlatch, Cyclicbarrier และ Exchanger
* ตัวอย่างนี้ส่วนใหญ่แนะนำ Semaphore
* Semaphore เป็นเครื่องมือที่ใช้ในการจัดการพูลทรัพยากรซึ่งถือได้ว่าเป็นบัตรผ่าน
* หากเธรดต้องการรับทรัพยากรจากพูลทรัพยากรจะต้องได้รับบัตรผ่านก่อน
* หากเธรดไม่สามารถผ่านได้ชั่วคราวเธรดจะถูกบล็อกและป้อนสถานะการรอคอย
-
MySemaphore คลาสสาธารณะขยายเธรด {
ส่วนตัว int i;
เซมาฟอร์เซมาฟอร์ส่วนตัว;
สาธารณะ mysemaphore (int i, semaphore semaphore) {
this.i = i;
this.semaphore = semaphore;
-
โมฆะสาธารณะเรียกใช้ () {
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 ()*10,000);
} catch (interruptedException e) {
E.PrintStackTrace ();
-
System.out.println (""+i+"ใช้อย่างสมบูรณ์");
semaphore.release ();
-
โมฆะคงที่สาธารณะหลัก (สตริง [] args) {
semaphore semaphore = semaphore ใหม่ (2);
ExecutorService Service = Executors.NewCachedThreadPool ();
สำหรับ (int i = 0; i <10; i ++) {
service.execute (ใหม่ mySemaphore (i, semaphore));
-
Service.shutdown ();
semaphore.acquireuntibly (2);
System.out.println ("ใช้ต้องทำความสะอาด");
semaphore.release (2);
-
-