Java concurrency deadlock instance, java dead instance

Source: Internet
Author: User

Java concurrency deadlock instance, java dead instance

 1 package com.thread.test.thread; 2  3 /** 4  * Created by windwant on 2016/6/3. 5  */ 6 public class MyTestDeadLock { 7     public void run() { 8         MyThread mt = new MyThread(); 9         new Thread(mt, "zhangsan").start();10         new Thread(mt, "lisi").start();11     }12 13     class MyThread implements Runnable {14         private Object o1 = new Object();15         private Object o2 = new Object();16         private boolean flag = true;17 18 19         public void run() {20             if (flag) {21                 flag = false;22                 synchronized (o1) {23                     System.out.println(Thread.currentThread().getName() + " have o1");24                     try {25                         Thread.sleep(100);26                     } catch (InterruptedException e) {27                         e.printStackTrace();28                     }29                     synchronized (o2) {30                         System.out.println(Thread.currentThread().getName() + " have o2");31                     }32                 }33             } else {34                 flag = true;35                 synchronized (o2) {36                     System.out.println(Thread.currentThread().getName() + " have o2");37                     try {38                         Thread.sleep(100);39                     } catch (InterruptedException e) {40                         e.printStackTrace();41                     }42                     synchronized (o1) {43                         System.out.println(Thread.currentThread().getName() + " have o1");44                     }45                 }46             }47         }48     }49 50     public static void main(String[] args) {51         new MyTestDeadLock().run();52     }53 }

Project address: https://github.com/windwant/threadtest

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.