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

  • 相关阅读:
    GRIDVIEW导出到EXCEL
    .NET GRIDVIEW导出EXCEL
    C#自动列宽
    vue 路由跳转及传值和取值
    vue 部署windows nginx服务上
    vue多个代理配置vue.config
    mock常用规则
    git基础篇-常见错误
    git基础篇-使用教程
    win10 gitserver搭建
  • 原文地址:https://www.cnblogs.com/helloworldlx/p/8536390.html
Copyright © 2011-2022 走看看