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

Java Se地图hore例子

2013-03-29 
Java Semaphore例子package player.kent.chen.learn.semaphoreimport java.util.concurrent.Semaphorepu

Java Semaphore例子

package player.kent.chen.learn.semaphore;import java.util.concurrent.Semaphore;public class HelloSemaphore {    private static final class Room {        //信号量作为共享资源的属性        private Semaphore semaPhore = new Semaphore(3, true);  //每次只允许3个人在房内         public void take() throws InterruptedException {            try {                semaPhore.acquire();                System.out.println(Thread.currentThread().getName() + " is now in the room");                Thread.sleep(3000);            } finally {                semaPhore.release();            }        }    }    private static final class Guest implements Runnable {        private Room room;        /**         * 进出房间的人         */        public Guest(Room room) {            super();            this.room = room;        }        public void run() {            while (true) {                try {                    room.take();                } catch (InterruptedException e) {                    throw new RuntimeException(e);                }            }        }    }    public static void main(String[] args) {        Room room = new Room();        Thread[] threads = new Thread[10];        for (int i = 0; i < threads.length; i++) {            threads[i] = new Thread(new Guest(room));            threads[i].setName("Thread-No-" + i);        }        for (Thread thread : threads) {            thread.start();        }    }}


观察控制台输出,可见每次只有3个线程获得资源

热点排行