java中死锁的例子

public class DemoApplication {

	private static String a = "12";
	private static String b = "34";

	public static void main(String[] args) {
		Thread t1 = new Thread(() -> {
			synchronized (a) {
				System.out.println("t1线程,进入a同步块, 执行中");
				try {
					Thread.sleep(2000);
					synchronized (b) {
						System.out.println("t1线程,进入b同步块,执行中");
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "thread1");

		Thread t2 = new Thread(() -> {
			synchronized (b) {
				System.out.println("t2线程,进入b同步块, 执行中");
				synchronized (a) {
					System.out.println("t2线程, 进入a同步块,执行中");
				}
			}
		}, "thread2");

		t1.start();
		t2.start();
	}

}

死锁

  • 使用jps查出当前的线程的pid
  • 使用jstack pid,查看当前栈信息,可以看到下面的栈信息,其中第一行,就有标出来deadlock,表示当前出现了死锁
Found one Java-level deadlock:
=============================
"thread1":
  waiting to lock monitor 0x00007fa666a0e000 (object 0x0000000783337e10, a java.lang.String),
  which is held by "thread2"
"thread2":
  waiting to lock monitor 0x00007fa666a07e00 (object 0x0000000783345dc0, a java.lang.String),
  which is held by "thread1"

Java stack information for the threads listed above:
===================================================
"thread1":
        at com.example.demo.DemoApplication.lambda$main$0(DemoApplication.java:21)
        - waiting to lock <0x0000000783337e10> (a java.lang.String)
        - locked <0x0000000783345dc0> (a java.lang.String)
        at com.example.demo.DemoApplication$$Lambda$74/0x0000000800136840.run(Unknown Source)
        at java.lang.Thread.run(java.base@11.0.6/Thread.java:834)
"thread2":
        at com.example.demo.DemoApplication.lambda$main$1(DemoApplication.java:33)
        - waiting to lock <0x0000000783345dc0> (a java.lang.String)
        - locked <0x0000000783337e10> (a java.lang.String)
        at com.example.demo.DemoApplication$$Lambda$75/0x0000000800136c40.run(Unknown Source)
        at java.lang.Thread.run(java.base@11.0.6/Thread.java:834)

Found 1 deadlock.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值