Java多线程死锁举例

package com.thread.dome;
 2 
 3 public class LockS implements Runnable{
 4 
 5     int i=0;
 6     LockS(int i){
 7         this.i=i;
 8         
 9     }
10     String lock1="lock1";//锁1
11     String lock2="lock2";//锁2
12     @Override
13     public void run() {
14         // TODO Auto-generated method stub
15         
16         if(i==1){
17             synchronized (lock1) {//占用锁1
18                 System.out.println("lock1 i=1");
19                 synchronized (lock2) {//等待获取锁2
20                     System.out.println("lock2 i=1");
21                 }
22             }
23             
24         }else{
25             synchronized (lock2) {//占用锁2
26                 System.out.println("lock2 i=2");
27                 synchronized (lock1) {//等待获取锁1
28                     System.out.println("lock1 i=2");
29                 }
30             }
31         
32         }
33         
34         
35     }
36     public static void main(String[] args) {
37         Thread t1=new Thread(new LockS(1));
38         Thread t2=new Thread(new LockS(2));
39         t1.start();
40         t2.start();
41     }
42 
43 }
44 
45 运行效果:
46 lock1 i=1
47 lock2 i=2

猜你喜欢

转载自www.cnblogs.com/mature1021/p/9493206.html