Super invincible multi-thread deadlock and Super invincible multi-thread in history
* Synchronized: the lock is an attribute of every object. synchronized only locks the lock and is a continuous action.
* Deadlocks are inaccessible to everyone.
*
* Two threads,
* Two threads successively access two mutually exclusive objects
*
* Principle:
* 1 when the execution of a thread is completed, two objects must be nested and locked. However, during the process, the first object must be locked.
* 2 If the execution of another thread is complete, you also need to lock the execution of two objects in nesting order. First, the execution locks the second object.
* 3 during the first execution, when the second object is executed, it is found that the object is locked. Wait
* 4 when the first object is executed in the second thread, it is found that the first object is locked and can only wait.
Public class Thread DeadLock {
Public static void main (String [] args ){
Object o1 = new Object ();
Object o2 = new Object ();
Thread t1 = new Thread (new A (o1, o2 ));
Thread t2 = new Thread (new B (o1, o2 ));
T1.start ();
T2.start ();
}
}
Class A implements Runnable {
Object o1;
Object o2;
T1 (Object o1, Object o2 ){
This. o1 = o1;
This. o2 = o2;
}
Public void run (){
Synchronized (o1 ){
Try {
Thread. sleep (1000 );
} Catch (Exception e ){
E. printStackTrace ();
}
Synchronized (o2 ){
System. out. println ("t1 ");
}
}
}
}
Class B implements Runnable {
Object o1;
Object o2;
T2 (Object o1, Object o2 ){
This. o1 = o1;
This. o2 = o2;
}
Public void run (){
Synchronized (o2 ){
Try {
Thread. sleep (1000 );
} Catch (Exception e ){
E. printStackTrace ();
}
Synchronized (o1 ){
System. out. println ("t2 ");
}
}
}
}