首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Se地图hore关于抢车位例子

2012-10-08 
Semaphore关于抢车位例子package com.testimport java.util.Randomimport java.util.concurrent.Executo

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();}}

热点排行