信号量的使用案例
import java.util.concurrent.Semaphore; public class SemaphoreLearn { public static void main(String[] args) { Semaphore semaphore = new Semaphore(5, true); int custom = 100; for (int i = 0; i < custom; i++) { new Thread(new Server(semaphore, i)).start(); } } } class Server implements Runnable { private Semaphore semaphore; private int custom; public Server(Semaphore semaphore, int custom) { this.semaphore = semaphore; this.custom = custom; } @Override public void run() { try { while(true) { //如果获取连接失败,则强制等待 /*if (semaphore.tryAcquire()) { Teller.getService(custom); break; }*/ semaphore.acquire(); //也可以通过这种方式进行,因为该方法是个阻塞方法 Teller.getService(custom); } } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } } class Teller { public static void getService(int i) { System.out.println("servering to custom " + i); } }
posted on 2015-12-24 16:19 zhaojunyang 阅读(396) 评论(0) 收藏 举报
浙公网安备 33010602011771号