死锁的代码,这样写对吗?
Java编写,死锁:
class HoldLock implements Runnable{
private String lockA;
private String lockB;
public HoldLock(String lockA,String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName()+"\t自己持有:"+lockA+"\t尝试获得"+lockB);
try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}
synchronized (lockB) {
System.out.println(Thread.currentThread().getName()+"\t自己持有:"+lockB+"\t尝试获得"+lockA);
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldLock(lockA,lockB),"ThreadAA").start();
new Thread(new HoldLock(lockB,lockA),"ThreadBB").start();
}
}
努力变秃吧!