黑马程序员技术交流社区
标题:
为什么这段代码实现不了死锁?
[打印本页]
作者:
王海龙
时间:
2012-12-22 21:41
标题:
为什么这段代码实现不了死锁?
public class Deadlock {
private String a="";
private String b="";
private int n=1;
public void write(){
synchronized (a) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (b) {
System.out.println("第" +
n+"次被写入");
n++;
}
}
}
public void read(){
synchronized (b) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (a) {
System.out.println("第" +
n+"次被读取");
n++;
}
}
}
复制代码
public class MyDeadlock implements Runnable{
private Deadlock dl;
public MyDeadlock(Deadlock dl) {
this.dl = dl;
}
@Override
public void run() {
for(int i=0;i<100;i++){
dl.write();
dl.read();
}
}
复制代码
public class TestDeadlock {
public static void main(String[] args) {
Deadlock deadlock=new Deadlock();
MyDeadlock md=new MyDeadlock(deadlock);
Thread t1=new Thread(md);
Thread t2=new Thread(md);
t1.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
复制代码
能sleep的地方都sleep了,就是不死锁,是不是什么地方有问题?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2