请使用Semaphore编写一个程序,实现以下效果: * 要求: * 1.有10名游客要参观展览室, * 2.展览室同时只允许最多“三个游客”参观, * 3.每个游客参观时间2秒。

public class TestDemo {
    public static void main(String[] args) {
        //1.创建Semaphore对象
        Semaphore semaphore = new Semaphore(3);

        //2.循环,开启10个线程
        for (int i = 0; i < 10; i++) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        // 获得参观权
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + ":开始参观-" + LocalTime.now());
                        // 参观 2s
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        // 释放参观权
                        semaphore.release();
                    }
                }
            }.start();
        }
    }
}
================================================
public class Test01 {
    public static void main(String[] args) {
        Semaphore s = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            MyThread myThread = new MyThread(s);
            myThread.start();
        }
    }
}
==========================================================
public class MyThread extends Thread {
    public Semaphore s;

    public MyThread(Semaphore s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            s.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(getName()+":"+"在参观");
        s.release();

    }
}
上一篇:Zip4j


下一篇:SemaphoreSlim类——控制访问某资源的线程数量