JUC并发编程死锁(二十)

死锁

JUC并发编程死锁(二十)_第1张图片

package com.xizi.lock;

import java.util.concurrent.TimeUnit;

public class DeadLock {
    public static void main(String[] args) {
        String lock1="lock1";
        String lock2="lock2";
        new Thread(new MyThread(lock1,lock2),"abc").start();
        new Thread(new MyThread(lock2,lock1),"abcd").start();

    }
}

class  MyThread implements  Runnable{
    private  String lockA;
    private String lockB;

    public  MyThread(String lockA,String lockB){
        this.lockA=lockA;
        this.lockB=lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"lock:"+lockA+"=>get:"+lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"lock:"+lockB+"=>get:"+lockA);

            }
        }
    }
}

解决问题

JUC并发编程死锁(二十)_第2张图片

JUC并发编程死锁(二十)_第3张图片

 

你可能感兴趣的:(JUC并发编程(Java))