Deadlock
java thread synchronization mechanism to solve the security problem, but also led to deadlock
The root causes of the phenomenon of deadlock
1. The existence of two or more threads.
2. The presence of two or more shared resources.
Solution to the deadlock problem
No program, only try to avoid it.
Example:
package jd1908_corejava.ch17; public class DeadLock { // 锁A public static Object A = new Object(); // 锁B public static Object B = new Object(); public static void main(String[] args) { T1 t1 = new T1(); T2 t2 = new T2(); t1.start(); t2.start(); } } class T1 extends Thread { @Override public void run() { synchronized (DeadLock.A) { System.out.println("A"); synchronized (DeadLock.B) { System.out.println("核心代码T1"); } } } } class T2 extends Thread { @Override public void run() { synchronized (DeadLock.B) { System.out.println("\tB"); synchronized (DeadLock.A) { System.out.println("Core code T2" ); } } } }
result:
A
B