• 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");
                        }
                    }
            }
        }
    }
  • 相关阅读:
    POJ 2388
    POJ 2387
    POJ 2389
    POJ 2379
    POJ 2385
    文件及输入输出流模拟ATM机
    文件及输入输出流模拟学生系统
    第六讲 字符串
    第四节课练习
    第四次上课练习
  • 原文地址:https://www.cnblogs.com/ql211lin/p/3971948.html
Copyright © 2020-2023  润新知