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个线程获得资源

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.