[英]Java synchronized vs deadlock example
I am not familiar with threads and concurrent programming. 我对线程和并发编程不熟悉。 I was looking for a simple snippet which would result in a deadlock, here it is : 我正在寻找一个简单的代码片段,它会导致死锁,这是:
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();
}
}
Now I was wondering how I could transform this example, using ReentrantLock instead of synchronized, but I don't see how : does fun need to have a ReentrantLock attribute in order to have something like 现在,我想知道如何使用ReentrantLock而不是sync来转换此示例,但我不知道如何:为了获得类似的东西,有趣的是需要具有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();}
}
}
}
}
};
or am I missing something entirely ? 还是我完全错过了什么?
Transforming the example using ReentrantLocks would indeed mean using two locks: one associated with d1
and the other one associated with d2
. 使用ReentrantLocks转换示例确实意味着要使用两个锁:一个与d1
关联,另一个与d2
关联。
And you would replace every entrance in a synchronized block on dX
by a call to lockX.lock()
, and any exit from a synchronized block on dX
by a call to lockX.unlock()`. 您将通过调用lockX.lock()
来lockX.lock()
dX
上同步块中的每个入口,并通过调用lockX.unlock()`来替换dX
上同步块中的所有出口。
Using tryLock()
defeats the purpose, since it returns instead of waiting if the lock can't be acquired. 使用tryLock()
达到目的,因为它返回而不是在无法获取锁的情况下等待。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.