Java Learning notes-interviewing regulars: writing a deadlock example

Source: Internet
Author: User

Now the interview is very egg pain, in order to examine everyone's language mastery level, similar to such a problem is particularly many, but in a certain angle can actually see a person's understanding of a certain knowledge point, such as today's small example of the deadlock, mainly to examine the thread deadlock concept of the understanding of the extent, Also look at the code level of the Java language, here is a simple example of a deadlock:

<span style= "FONT-SIZE:18PX;" >class Test implements Runnable{private Boolean flag;//flag tag to allow T1 and T2 threads to execute different code public Test (Boolean flag) {this.flag= Flag;} public void Run () {if (flag)  {synchronized (mylock.lock1) {System.out.println ("if1"); synchronized (Mylock.lock2) { System.out.println ("If2");}}} Else{synchronized (Mylock.lock2) {System.out.println ("Else2"); synchronized (MYLOCK.LOCK1) {System.out.println (" Else1 ");}}}} Class MyLock  //Two locks, used to create a deadlock {public static object lock1 = new Object ();p ublic static Object Lock2 = new Object ();} Class DeadLock {public static void main (string[] args) {Thread T1 = new Thread (new Test (true))//t1 first with lock 1 again with lock 2Thread t2 = n EW Thread (new Test (false));//t2 first with lock 2 again with lock 1t1.start (); T2.start ();}} </span>


Java Learning notes-interviewing regulars: writing a deadlock example

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: [email protected] 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.