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

  • 相关阅读:
    在openwrt上初体验PostgreSQL数据库
    Linux学习笔记(7)-系统资源查看
    Linux学习笔记(6)-工作管理
    Linux学习笔记(5)-进程管理
    Linux学习笔记(4)-文本编辑器vi的使用
    linux学习笔记(3)-文件系统
    Linux学习笔记(2)-用户和用户组
    linux学习笔记(1)-文件处理相关命令
    68.vivado与modelsim的关联以及器件库编译
    67.ARP协议
  • 原文地址:https://www.cnblogs.com/helloworldlx/p/8536390.html
Copyright © 2011-2022 走看看