zoukankan      html  css  js  c++  java
  • 使用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可有由其他的线程来释放

  • 相关阅读:
    基本sql查询语句练习
    SZU:J38 Number Base Conversion
    SZU:B54 Dual Palindromes
    SZU:A66 Plastic Digits
    HOJ:2031 进制转换
    SZU:G34 Love code
    SZU:A25 Favorite Number
    Vijos:P1001谁拿了最多奖学金
    SZU:A26 Anagram
    SZU:A12 Jumping up and down
  • 原文地址:https://www.cnblogs.com/moris5013/p/11876794.html
Copyright © 2011-2022 走看看