读书人

Se地图hore关于抢车位例子

发布时间: 2012-10-08 19:54:56 作者: rapoo

Semaphore关于抢车位例子

package com.test;import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class SemaphoreTest{/** * @param args */public static void main(String[] args){ExecutorService pool = Executors.newCachedThreadPool();final Semaphore sp = new Semaphore(3); // 3个车位for (int i = 0; i < 10; i++){pool.execute(new Runnable(){public void run(){try{sp.acquire();System.out.println("小车:" + Thread.currentThread().getName()+ "已抢到车位,还有"+sp.availablePermits()+"个车位");Thread.sleep(new Random().nextInt(10000));sp.release();System.out.println("小车:" + Thread.currentThread().getName()+ "离开车位,还有"+sp.availablePermits()+"个车位");}catch (Exception e){e.printStackTrace();}}});}pool.shutdown();}}

读书人网 >编程

热点推荐