• 模拟死锁


    package com.roocon.thread.t6;
    
    public class Demo3 {
        private Object obj1 = new Object();
        private Object obj2 = new Object();
    
        public void a(){
            synchronized (obj1){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj2){
                    System.out.println("a");
                }
            }
        }
    
        public void b(){
            synchronized (obj2){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj1){
                    System.out.println("b");
                }
            }
        }
    
        public static void main(String[] args) {
            Demo3 demo3 = new Demo3();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo3.a();
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    demo3.b();
                }
            }).start();
        }
    
    }

    运行结果:

    控制台一直在运行,但是无任何输出。

    通过命令检测是否真的发生了死锁:

    点击线程,检测死锁:

  • 相关阅读:
    架构师之路
    责任链设计模式
    Junit框架分析
    线程详解
    课程总结
    IO流
    Java第四次作业
    Character string
    实训
    实训SI
  • 原文地址:https://www.cnblogs.com/sunnyDream/p/8135324.html
Copyright © 2020-2023  润新知