使用semaphore写一个显示锁

只愿长相守 提交于 2019-12-04 18:08:13
public class SemaphoreLock {

    private final Semaphore semaphore = new Semaphore(1);

    public void lock() throws InterruptedException {
        semaphore.acquire();
    }

    public void  unlock(){
        semaphore.release();
    }

    public static void main(String[] args) {
        SemaphoreLock lock = new SemaphoreLock();

        for(int i=0; i<2; i++){
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName() + " is running ");
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " get the lock ");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
                System.out.println(Thread.currentThread().getName() + " release  the lock ");
            }).start();
        }
    }


}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!