deadlockdemo.java

来自「JAVA编程思想源代码 值得一下 很难找的」· Java 代码 · 共 52 行

JAVA
52
字号
package chapter13;

public class DeadLockDemo implements Runnable {

	class A {
		synchronized void a(B b) throws InterruptedException {
			System.out.println(Thread.currentThread().getName() + "进入到A类中的方法");
			Thread.sleep(1000); //给一定的时间让别的线程运行,创造死锁的条件
			b.dead();
		}

		synchronized void dead() {
			System.out.println("dead");
		}
	}

	class B {
		synchronized void b(A a) throws InterruptedException {
			System.out.println(Thread.currentThread().getName() + "进入到B类中的方法");
			Thread.sleep(1000); //给一定的时间让别的线程运行,创造死锁的条件
			a.dead();
		}

		synchronized void dead() {
			System.out.println("dead");
		}
	}

	public A a = new A();

	public B b = new B();

	public DeadLockDemo() throws InterruptedException {
		Thread.currentThread().setName("主线程");
		new Thread(this, "其他线程").start();
		a.a(b);
		System.out.println("回到主线程");
	}

	public void run() {
		try {
			b.b(a);
		} catch (InterruptedException ie) {
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new DeadLockDemo();
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?