可以产生死锁的代码

时间:2021-08-08 20:51:09

面试的时候,可能会有个考题:请给我写一个死锁程序。

考的是你对死锁的理解!

代码:

class Test implements Runnable{
private boolean flag;
Test(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
synchronized(MyLock.locka){
System.out.println("if locka");
synchronized (MyLock.lockb) {
System.out.println("if lockb");
}
}
}else{
synchronized(MyLock.lockb){
System.out.println("else lockb");
synchronized (MyLock.locka) {
System.out.println("else locka");
}
}
}
}
}
class MyLock{
static Object locka = new Object();
static Object lockb = new Object();
}
public class DeadLockTest {

public static void main(String[] args) {
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}

说明:
以上程序运行后,有可能会产生死锁现象,也有可能不会产生死锁现象,看情况而论!