zoukankan      html  css  js  c++  java
  • 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");
                        }
                    }
            }
        }
    }
  • 相关阅读:
    JSP基础语法:注释、Scriptlet、编译指令
    JDBC的LIKE书写规范
    AWT回顾篇
    1.五子棋预备知识
    对象的生命周期回顾篇
    学习activemq(2)写个简单的程序
    activemq in action(3)剖析JMS消息(转)
    activemq in action(1)
    学习activemq(3)
    hadhoop安装
  • 原文地址:https://www.cnblogs.com/ql211lin/p/3971948.html
Copyright © 2011-2022 走看看