java

Java并发-死锁

1.2死锁

public class DeadLockDemo {
	privat static String A = "A";
	private static String B = "B";
	public static void main(String[] args) {
		new DeadLockDemo().deadLock();
	}
	private void deadLock() {
		Thread t1 = new Thread(new Runnable() {
			@Override
			publicvoid run() {
				synchronized (A) {
					try { 
						Thread.currentThread().sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (B) {
						System.out.println("1");
					}
			 	}
			}
		});
		Thread t2 = new Thread(new Runnable() {
			@Override
			publicvoid run() {
				synchronized (B) {
					synchronized (A) {
						System.out.println("2");
					}
				}
			}
		});
		t1.start();
		t2.start();
	}
}

死锁线程状态:

“Thread-2” prio=5 tid=7fc0458d1000 nid=0x116c1c000 waiting for monitor entry [116c1b00java.lang.Thread.State: BLOCKED (on object monitor) at com.ifeve.book.forkjoin.DeadLockDemo$2.run(DeadLockDemo.java:42) waiting to lock <7fb2f3ec0> (a java.lang.String) locked <7fb2f3ef8> (a java.lang.String) at java.lang.Thread.run(Thread.java:695)

“Thread-1” prio=5 tid=7fc0430f6800 nid=0x116b19000 waiting for monitor entry [116b1800java.lang.Thread.State: BLOCKED (on object monitor) at com.ifeve.book.forkjoin.DeadLockDemo$1.run(DeadLockDemo.java:31) waiting to lock <7fb2f3ef8> (a java.lang.String) locked <7fb2f3ec0> (a java.lang.String) at java.lang.Thread.run(Thread.java:695)

关于作者

程序员,软件工程师,java, golang, rust, c, python,vue, Springboot, mybatis, mysql,elasticsearch, docker, maven, gcc, linux, ubuntu, centos, axum,llm, paddlepaddle, onlyoffice,minio,银河麒麟,中科方德,rpm