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();
        }
  • 相关阅读:
    密码安全等级效果
    随机生成不区分大小写的验证码
    css3的box方法实现文本水平垂直居中
    echarts省市地图显示
    mysql 连接数据库
    mysql 高版本order by 报错解决方案
    mysql 命令行操作
    mac本地运行php文件
    js 获取url参数
    js 每三位数添加逗号
  • 原文地址:https://www.cnblogs.com/brxHqs/p/9847986.html
Copyright © 2011-2022 走看看