zoukankan      html  css  js  c++  java
  • 手写一个死锁

    手写一个死锁、死锁满足的条件

    1、至少有两个线程互相争夺共享资源

    2、至少有两把锁两个线程分别持有锁

    两个线程各自持有一把锁并且企图获取到对方的正在持有的锁

    package demos;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * 写一个死锁第一种写法
     */
    public class DeadLock {
        public static void main(String[] args) {
            String a = "a";
            String b = "b";
    
            new Thread(new Resource(a,b),"ThreadA").start();
            new Thread(new Resource(b,a),"ThreadB").start();
        }
    }
    
    class Resource implements Runnable{
    
        String a;
        String b;
    
        public Resource(String a,String b){
            this.a = a;
            this.b = b;
        }
    
        @Override
        public void run() {
            synchronized (a){
                System.out.println(Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(2L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b){
                    System.out.println(Thread.currentThread().getName());
                }
            }
        }
    }
    package demos;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * 写一个死锁第二种写法用lock
     */
    public class DeadLock1 {
        public static void main(String[] args) {
            Lock lock1 = new ReentrantLock();
            Lock lock2 = new ReentrantLock();
    
            new Thread(new Resource1(lock1,lock2),"A").start();
            new Thread(new Resource1(lock2,lock1),"B").start();
    
        }
    }
    class Resource1 implements Runnable{
    
        Lock lock1;
        Lock lock2;
    
        public Resource1(Lock lock1,Lock lock2){
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
    
        @Override
        public void run() {
            lock1.lock();
            try{
    
                System.out.println(Thread.currentThread().getName());
                Thread.sleep(2);
                lock2.lock();
                try{
                    System.out.println(Thread.currentThread().getName());
                }finally {
                    lock2.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        }
    }
  • 相关阅读:
    20180929 北京大学 人工智能实践:Tensorflow笔记02
    20180929 北京大学 人工智能实践:Tensorflow笔记01
    YOLOv3学习笔记
    编辑器上传漏洞
    IIS解析漏洞利用
    数据库备份及审查元素进行webshell上传
    burp suite 进行webshell上传
    BUGKU CFT初学之WEB
    CTFbugku--菜鸟初学
    理解PHP中的会话控制
  • 原文地址:https://www.cnblogs.com/yangenyu/p/11545072.html
Copyright © 2011-2022 走看看