Discuss / Java / 练习:修复死锁

练习:修复死锁

Topic source

D

#1 Created at ... [Delete] [Delete and Lock User]

程序输出:

Thread-1: try get lock A...

Thread-1: lock A got. // 线程1此时处于Time Waiting状态,仍持有lock A

Thread-2: try get lock A... // 线程2申请获取lock A,处于Waiting状态(?) 

Thread-1: try get lock B... // 线程1被唤醒,继续运行

Thread-1: lock B got.

Thread-1: lock B released.

Thread-1: lock A released.

Thread-2: lock A got.

Thread-2: try get lock B...

Thread-2: lock B got.

Thread-2: lock B released.

Thread-2: lock A released.

代码:

package com.itranswarp.learnjava;



/**

 * Learn Java from https://www.liaoxuefeng.com/

 * 

 * @author liaoxuefeng

 */

public class Main {



	static final Object LOCK_A = new Object();

	static final Object LOCK_B = new Object();



	public static void main(String[] args) {

		new Thread1().start();

		new Thread2().start();

	}



	static void sleep1s() {

		try {

			Thread.sleep(1000);

		} catch (InterruptedException e) {

			e.printStackTrace();

		}

	}

}



class Thread1 extends Thread {



	public void run() {

		System.out.println("Thread-1: try get lock A...");

		synchronized (Main.LOCK_A) {

			System.out.println("Thread-1: lock A got.");

			Main.sleep1s();

			System.out.println("Thread-1: try get lock B...");

			synchronized (Main.LOCK_B) {

				System.out.println("Thread-1: lock B got.");

				Main.sleep1s();

			}

			System.out.println("Thread-1: lock B released.");

		}

		System.out.println("Thread-1: lock A released.");

	}

}



class Thread2 extends Thread {



	public void run() {

		System.out.println("Thread-2: try get lock A...");

		synchronized (Main.LOCK_A) {

			System.out.println("Thread-2: lock A got.");

			Main.sleep1s();

			System.out.println("Thread-2: try get lock B...");

			synchronized (Main.LOCK_B) {

				System.out.println("Thread-2: lock B got.");

				Main.sleep1s();

			}

			System.out.println("Thread-2: lock B released.");

		}

		System.out.println("Thread-2: lock A released.");

	}

}




  • 1

Reply