Super invincible multi-thread deadlock and Super invincible multi-thread in history

Source: Internet
Author: User

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 ");
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.