其他分享
首页 > 其他分享> > 死锁——从产生到消除

死锁——从产生到消除

作者:互联网

1、死锁是什么?

 

2、多个线程造成死锁的情况

3、死锁的影响

死锁的影响在不同系统中是不一样的,这取决于系统对死锁的处理能力

4、几率不高但是危害大

5、死锁的代码

package deadlock;

//描述:   必定发生死锁的情况
public class MustDeadLock implements Runnable {
    int flag = 1;

    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        MustDeadLock r1 = new MustDeadLock();
        MustDeadLock r2 = new MustDeadLock();
        r1.flag = 1;
        r1.flag = 0;
        Thread thread1 = new Thread(r1);
        Thread thread2 = new Thread(r2);
        thread1.start();
        thread2.start();
    }

    @Override
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    System.out.println("我拿到O1锁啦");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("我拿不到了");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    System.out.println("我拿了o2锁啦");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("拿不到了");
                }
            }
        }
    }
}

标签:Thread,产生,flag,死锁,o1,thread1,o2,消除
来源: https://blog.csdn.net/qq_56572867/article/details/122156388