使用semaphore写一个显示锁

/**
 * 这里只是将Semaphore包装了一下,注意当Semaphore的构造参数是1时,本身就是一个显示锁
 */
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();
        }
    }


}

 

这个例子就是把semaphore当成了普通的显示锁

public class SemaphoreLock {
    public static void main(String[] args) {
        //1、信号量为1时 相当于普通的锁  信号量大于1时 共享锁
        Output o = new Output();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> o.output()).start();
        }
    }
}
class Output {
    Semaphore semaphore = new Semaphore(1);

    public void output() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " start at " + System.currentTimeMillis());
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " stop at " + System.currentTimeMillis());
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
        }
    }
}

 

note:这里的semaphore只是当成了"lock",与真实的lock的区别是,真实的lock必须由lock的持有者进行释放,而semaphore可有由其他的线程来释放

posted @ 2019-11-17 15:53  踏月而来  阅读(296)  评论(0编辑  收藏  举报