zoukankan      html  css  js  c++  java
  • 死锁,活锁例子

    //死锁实例:
    @AllArgsConstructor
    @Data
    class MyRunnable implements Runnable{
    private String lockA;
    private String lockB;


    @Override
    public void run() {
    synchronized (lockA){
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("获得锁"+lockA+",尝试获取"+lockB);
    synchronized (lockB){
    System.out.println("已经尝试获得锁"+lockB);
    }
    }
    }
    }
        public static void main(String[] args) {
    String lockA = "lockA";
    String lockB = "lockB";
    new Thread(new MyRunnable(lockA,lockB)).start();
    new Thread(new MyRunnable(lockB,lockA)).start();
    }

    活锁

        /**
         * 活锁
         * @param args
         * @throws InterruptedException
         */
        public static void main(String[] args) throws InterruptedException {
            ReentrantLock A = new ReentrantLock();
            ReentrantLock B = new ReentrantLock();
            new Thread(() -> {
                boolean noOkflag = true;
                while (noOkflag) {
                    if (A.tryLock()){
                        System.out.println(Thread.currentThread()+"成功获取锁A");
                    }
                    if (B.tryLock()) {
                        System.out.println(Thread.currentThread()+"====================成功获取锁B");
                        B.unlock();
                        noOkflag = false;
                    }
                    if (A.isLocked()) {
                        A.unlock();
                    }
                }
            }).start();
    
            new Thread(() -> {
                boolean noOkflag = true;
                while (noOkflag) {
                    if (B.tryLock()) {
                        System.out.println(Thread.currentThread() + "成功获取锁B");
                    }
                    if (A.tryLock()) {
                        System.out.println(Thread.currentThread() + "=====================成功获取锁A");
                        A.unlock();
                        noOkflag = false;
                    }
                    if (B.isLocked()) {
                        B.unlock();
                    }
                }
            }).start();
        }
  • 相关阅读:
    学习篇之String()
    js之Math对象
    js之date()对象
    css之描点定位方式
    js详解之作用域-实例
    js精要之构造函数
    js精要之继承
    js精要之模块模式
    js精要之对象属性
    js精要之函数
  • 原文地址:https://www.cnblogs.com/brxHqs/p/9847986.html
Copyright © 2011-2022 走看看