• java的一个简单死锁的例子


    package com.deadlock;
    
    /*
     * 演示死锁:(由毕向东视频所得)
     * 一种解释:Thread—0拿到lock1锁,Thread—1拿到lock2锁,Thread—0想要lock2锁而Thread-1想要lock1锁,
     * 两个线程都无法继续执行下去,产生死锁。
     * 执行结果:Thread-0 if.....lock1
     *      Thread-1 else....lock2
     */
    public class DeadLockDemo {
    
        public static void main(String[] args) {
            Test a = new Test(true);
            Test b = new Test(false);
            Thread t1 = new Thread(a);
            Thread t2 = new Thread(b);
            t1.start();
            t2.start();
        }
    
    }
    
    class MyLock {
        public static final Object lock1 = new Object();
        public static final Object lock2 = new Object();
    
    }
    
    class Test implements Runnable {
        private boolean flag;
    
        public Test(boolean flag) {
            this.flag = flag;
        }
    
        public void run() {
            if (flag) {
                while (true)
                    synchronized (MyLock.lock1) {
                        System.out.println(Thread.currentThread().getName() + " if.....lock1");
                        synchronized (MyLock.lock2) {
                            System.out.println(Thread.currentThread().getName() + " if....lock2");
                        }
                    }
            } else {
                while (true)
                    synchronized (MyLock.lock2) {
                        System.out.println(Thread.currentThread().getName() + " else....lock2");
    
                        synchronized (MyLock.lock1) {
                            System.out.println(Thread.currentThread().getName() + " else.....lock1");
                        }
                    }
            }
        }
    }
  • 相关阅读:
    discuz开发笔记
    响应式布局
    timedelta
    图片轮播
    性能
    事件捕获
    git
    css hacks
    AFNetworking 网络错误提示data转换字符串
    常见HTTP错误代码
  • 原文地址:https://www.cnblogs.com/ql211lin/p/3971948.html
Copyright © 2020-2023  润新知