La copie de code est la suivante:
Package com.yao;
Importer java.util.concurrent.executorService;
Importer java.util.concurrent.executors;
import java.util.concurrent.semaphore;
/ **
* Java 5.0里新加了4个协调线程间进程的同步装置,它们分别是:
* Semaphore, CountDownLatch, CyclicBarrier和Exchanger.
* Cet exemple introduit principalement le sémaphore.
* Le sémaphore est un outil utilisé pour gérer un pool de ressources, qui peut être considéré comme une passe.
* Si un fil veut obtenir des ressources à partir du pool de ressources, il doit d'abord obtenir un laissez-passer.
* Si le thread ne peut pas obtenir la passe temporairement, le thread sera bloqué et entré dans un état d'attente.
* /
La classe publique MySemaphore étend Thread {
Int privé I;
Sémaphore de sémaphore privé;
MySemaphore public (int i, sémaphore sémaphore) {
this.i = i;
this.semaphore = sémaphore;
}
public void run () {
if (semaphore.availablePermits ()> 0) {
System.out.println ("" + i + "Il y a des espaces disponibles:");
}autre{
System.out.println(""+i+"等待,没有空位");
}
essayer {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace ();
}
System.out.println(""+i+"获得空位");
essayer {
Thread.sleep ((int) math.random () * 10000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
System.out.println ("" + i + "complètement utilisé");
Semaphore.release ();
}
public static void main (String [] args) {
Semaphore Semaphore = nouveau sémaphore (2);
ExecutorService Service = exécutor.NewCachedThreadPool ();
pour (int i = 0; i <10; i ++) {
Service.Execute (New MySemaphore (I, Semaphore));
}
service.shutdown ();
Semaphore.ACQUIREUNTERRUBLIBLY (2);
System.out.println("使用完毕,需要清扫了");
semaphore.release(2);
}
}