zoukankan      html  css  js  c++  java
  • 使用内部类实现线程死锁

    线程死锁会不断消耗资源,禁止使用。本文纯属娱乐。

    在使用synchronized嵌套的时候很容易出现死锁现象,因此慎用synchronized嵌套。

    public class TestDeadLock {

      public static void main(String [] args) {
        new TestDeadLock().show();
      }

      public void show() {
        DeadLock dl = new DeadLock();
        Thread tdl1 = new Thread(dl, "老王");
        Thread tdl2 = new Thread(dl, "小王");

        tdl1.start();
        tdl2.start();
        }

      class DeadLock implements Runnable{
        private Object key1 = new Object();
        private Object key2 = new Object();
        private boolean isFlag;

        @Override
        public void run() {
          if(!isFlag) {
            isFlag = true;
            synchronized(key1) {
              System.out.println(Thread.currentThread().getName() + "拿到了key1");
              synchronized(key2) {
                System.out.println(Thread.currentThread().getName() + "拿到了key2");
              }
            }
          }else {
            isFlag = false;
            synchronized(key2) {
              System.out.println(Thread.currentThread().getName() + "拿到了key2");
              synchronized(key1) {
                System.out.println(Thread.currentThread().getName() + "拿到了key1");
              }
            }
          }
        }

        public boolean isFlag() {
          return isFlag;
        }

        public void setFlag(boolean isFlag) {
          this.isFlag = isFlag;
        }
      }
    }

  • 相关阅读:
    JS 深拷贝方法
    数字图像处理中的混叠
    RoIAlign理解
    关于python项目vscode 提示import could not be resolved的问题解决
    HTTPS网站证书申请,HTTPS的安全特性
    使用多域名SSL证书 一种免费的证书申请方式
    During secondary validation: DNS problem: query timed out looking up CAA for ***
    The Next Gen Database Servers Powering Let's Encrypt
    Jenkins 构建及回滚任务
    Go优雅追踪堆栈错误包
  • 原文地址:https://www.cnblogs.com/helloworldlx/p/8536390.html
Copyright © 2011-2022 走看看