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

  • 相关阅读:
    ubuntu下安装gcc,g++
    React Native核心组件View的介绍
    React Native组件生命周期
    React Native的props和state的介绍
    android出现anr(application not response)的分析
    HDU 2050:折线分割平面
    Codeforces 989A:A Blend of Springtime
    Codeforces 990B :Micro-World
    51Nod 1089:最长回文子串 V2(Manacher算法)
    51Nod 1088:最长回文子串(暴力)
  • 原文地址:https://www.cnblogs.com/helloworldlx/p/8536390.html
Copyright © 2011-2022 走看看