程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java並發之死鎖實例,java之死實例

Java並發之死鎖實例,java之死實例

編輯:JAVA綜合教程

Java並發之死鎖實例,java之死實例


 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 }

項目地址:https://github.com/windwant/threadtest

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved