使用semaphore写一个显示锁

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();
        }
    }


}

 

上一篇:自旋锁


下一篇:JavaWeb学习篇之----EL表达式详解