我不熟悉线程和并发编程。我正在寻找一个会导致死锁的简单片段,这里是:
public class TestLock {
private static class fun {
int a,b;
void read() {System.out.println(a+b);}
void write(int a,int b) {this.a=a;this.b=b;}
}
public static void main (String[] args) throws java.lang.Exception {
final fun d1=new fun();
final fun d2=new fun();
Thread t1=new Thread() {
public void run() {
for(int i=0;i<5;i++) {
synchronized(d2) {
d2.read();
try {
Thread.sleep(50);
} catch (Exception ex) {
ex.printStackTrace();
}
synchronized(d1) {
d1.write(i, i);
}
}
}
};
Thread t2=new Thread() {
public void run() {
for(int i=0;i<5;i++) {
synchronized(d1) {
d1.read();
try {
Thread.sleep(50);
} catch (Exception ex) {
ex.printStackTrace();
}
synchronized(d2) {
d2.write(i, i);
}
}
}
}
};
t1.start();
t2.start();
}
}
现在我想知道如何转换这个例子,使用 ReentrantLock 而不是同步,但我不明白:fun 是否需要有一个 ReentrantLock 属性才能有类似的东西
Thread t1=new Thread() {
public void run() {
for(int i=0;i<5;i++) {
if(d2.lock.tryLock()) {
try {d1.read();Thread.sleep(50);} catch(Exception e) {e.printStackTrace();} finally {d1.lock.unlock();}
if(d2.lock.tryLock()) {
try {d2.write(i, i);} catch(Exception e) {e.printStackTrace();} finally {d2.lock.unlock();}
}
}
}
}
};
还是我完全错过了什么?