class Test implements Runnable{
private boolean flag;
Test(boolean flag){
this.flag=flag;
}
public void run(){//实现Runnable接口,复写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 DeadLockDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1=new Thread(new Test(true));
Thread t2=new Thread(new Test(false));
t1.start();
t2.start();
}
}
在职场面试中,有好多面试题要求写出一个死锁,上面的这个是经典的死锁,在面试中很可能就能够帮助到你!
----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------