双线程死锁程序

  • Post author:
  • Post category:其他


直接上代码。

import java.time.chrono.ThaiBuddhistEra;

/**
 *
 * 多个线程互相拿着对方的资源,然后形成僵持
 */


public class DeadLock{
    public static void main(String[] args) {
        Go go = new Go(0,"小花");
        Go go1 = new Go(1,"小红");
        Thread thread = new Thread(go);
        Thread thread1 = new Thread(go1);
        thread.start();
        thread1.start();
    }
}

// 吃饭
class Eat{

}

// 洗手
class Wash{

}

class Go implements Runnable{

    //需要的资源只有一份,用static来保证
    static Eat eat = new Eat();
    static Wash wash = new Wash();

    int choice; // 选择
    String name;
    Go(int choice,String name){
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            go();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void go() throws InterruptedException {
        if (choice == 0) {
            synchronized (eat) { // 获得吃饭的锁
                System.out.println(Thread.currentThread().getName() + "获得吃饭的锁");
                Thread.sleep(1000);
                synchronized (wash) { // 一秒后想获得洗手的锁.
                    System.out.println(Thread.currentThread().getName() + "获得洗手的锁");
                }
            }
        }else {
            synchronized (wash) {
                System.out.println(Thread.currentThread().getName() + "获得吃饭的锁");
                Thread.sleep(2000);
                synchronized (eat) {
                    System.out.println(Thread.currentThread().getName() + "获得洗手的锁");
                }
            }
        }
    }
}



版权声明:本文为weixin_44164943原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。