java死锁示例代码

public class DeadLock { public static String obj1 = "obj1"; public static String obj2 = "obj2"; public static void main(String[] args) { Thread thread...
public class DeadLock {

    public static String obj1 = "obj1";
    public static String obj2 = "obj2";

    public static void main(String[] args) {

        Thread thread1 = new Thread(new Lock1());
        Thread thread2 = new Thread(new Lock2());
        thread1.start();
        thread2.start();

    }
}

    class Lock1 implements Runnable{

        @Override
        public void run() {
            try {
                System.out.println("Lock1 runing!");
                while (true){
                    synchronized(DeadLock.obj1){
                        System.out.println("Lock1 lock obj1");
                        Thread.sleep(3000);
                        synchronized (DeadLock.obj2){
                            System.out.println("Lock1 lock obj2");
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    class Lock2 implements Runnable{

        @Override
        public void run() {
            try {
                System.out.println("Lock2 runing!");
                while (true){
                    synchronized(DeadLock.obj2){
                        System.out.println("Lock2 lock obj2");
                        Thread.sleep(3000);
                        synchronized (DeadLock.obj1){
                            System.out.println("Lock2 lock obj1");
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

  • 发表于 2019-09-05 15:00
  • 阅读 ( 91 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除