在面试的过程中可能会要求写出一个死锁的例子:
public class Lock implements Runnable{
public static Object o1=new Object();
public static Object o2=new Object();
int flage;
public Lock(int flage){
this.flage=flage;
}
@Override
public void run() {
if(flage==1){
synchronized(o1){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o2){
System.out.println("没有锁住");
}
}
}
else{
synchronized(o2){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(o1){
System.out.println("没有锁住");
}
}
}
}
public static void main(String[] args){
Lock lcok1=new Lock(1);
Lock lcok2=new Lock(2);
Thread thread1=new Thread(lcok1);
Thread thread2=new Thread(lcok2);
thread1.start();
thread2.start();
}
}
死锁的例子很简单。