线程死锁demo

public class DeadLock implements Runnable {
    //为什么用static object?因为不使用static,那么deadLock1,deadLock2都会有自己的私有变量,也就是说每个线程取得互斥锁时,会访问属于自己的object1,object2,但是如果两个对象共享object,每个线程就会争抢object
    private static Object object1=new Object();
    private static Object object2=new Object();
    private int flag;
    public void run() {
        System.out.println(Thread.currentThread().getName()+" flag:"+flag);
        if(1==flag){
             synchronized (object1) {//当前线程不释放object1这个锁的同时,需要object2的锁,但是object2的锁,被其他线程占用,其他线程想要object1的锁
                 try {
                     Thread.sleep(500);
                 } catch (InterruptedException e) {
                     e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                 }
                 synchronized (object2){
                     System.out.println(0);
                 }
             }

        }

        if(0==flag){
            synchronized (object2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                synchronized (object1){
                    System.out.println(1);
                }
            }

        }
    }

    public static void main(String[] args) {
        DeadLock deadLock1 = new DeadLock();
        DeadLock deadLock2 = new DeadLock();
        deadLock1.flag=1;
        deadLock2.flag=0;
        Thread thread1 = new Thread(deadLock1);
        Thread thread2 = new Thread(deadLock2);
        thread1.setName("thread1");
        thread2.setName("thread2");

        thread1.start();
        thread2.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值