zoukankan      html  css  js  c++  java
  • 死锁

    例子

    package com.test.demo;
    
    /**
     * Created by admin on 2017/6/12 10:00.
     */
    public class DemoThread implements Runnable {
        /**
         * 被锁的对象要是同一个对象,即被 static 修饰,
         * 全局共享对象,不然多线程中 object1,object2 new出来的不是同一对象
         */
        static Object object1 = new Object();
        static Object object2 = new Object();
        boolean flag;
    
        DemoThread(boolean flag) {
            this.flag = flag;
        }
    
        @Override
        public void run() {
            if (flag) {
                synchronized (object1) {
                    System.out.println("if object1 adress:" + Integer.toHexString(object1.hashCode()));
                    synchronized (object2) {
                        System.out.println("if object2 adress:" + Integer.toHexString(object2.hashCode()));
                    }
                }
            } else {
                synchronized (object2) {
                    System.out.println("else object2 adress:" + Integer.toHexString(object2.hashCode()));
                    synchronized (object1) {
                        System.out.println("else object1 adress:" + Integer.toHexString(object1.hashCode()));
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            Thread t1 = new Thread(new DemoThread(true));
            Thread t2 = new Thread(new DemoThread(false));
            t1.start();
            try {
                Thread.sleep(5);
            } catch (Exception e) {
    
            }
            t2.start();
        }
    
    }

     

  • 相关阅读:
    oracle 编译无效对象
    nginx配置监控
    Docker底层技术
    KVM入门
    maven 忽略checkstyle
    Java 使用 UnixSocket 调用 Docker API
    unix-socket-implementation-for-java
    NVIDIA Physix Unity3D
    Mobile Prototype Dev Res Collection(Unity原型开发资源储备)
    Unity抗锯齿
  • 原文地址:https://www.cnblogs.com/skyessay/p/6991609.html
Copyright © 2011-2022 走看看