直接上代码吧:
package com.sanhu.utils;
public class DeckLockTest implements Runnable{
private int flag;
/**
* 这里必须使用static关键字进行修饰,来保证这两个对象对DeckLockTest的所有实例是共享的
* 如果不使用static修饰,不会产生死锁现象
*/
private static Object o1 = new Object(), o2 = new Object();
public DeckLockTest(int flag) {
this.flag = flag;
}
@Override
public void run() {
System.err.println("start: " + flag);
if(flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
synchronized (o2) {
System.err.println(flag);
}
}
}
if(flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
synchronized (o1) {
System.err.println(flag);
}
}
}
}
public static void main(String[] args) {
DeckLockTest t1 = new DeckLockTest(1);
DeckLockTest t2 = new DeckLockTest(0);
new Thread(t1).start();
new Thread(t2).start();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
实现的关键是两个线程竞争两个锁。