Java中信号量Semaphore的简单使用;
假设有3个人去银行办事,只有2个柜员,3人同时到达后须有一人等待,等待前两人办完之后再进行
import java.util.concurrent.Semaphore; public class SemaphoreTest { public static void main(String[] args) { Semaphore semaphore = new Semaphore(2); Person pA = new Person(semaphore, "A"); pA.start(); Person pB = new Person(semaphore, "B"); pB.start(); Person pC = new Person(semaphore, "C"); pC.start(); } } class Person extends Thread { private Semaphore semaphore; public Person(Semaphore semaphore, String name) { setName(name); this.semaphore = semaphore; } public void run() { System.out.println(getName() + "正在等待"); try { semaphore.acquire(); System.out.println(getName() + "正在服务"); sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } semaphore.release(); System.out.println(getName() + "完成服务"); } }