菜鸟之前在求职一些公司里笔试里会有死锁代码书写的要求,这里有非常简单的代码展示,首先你要懂得什么是死锁,如下`
public class DeadThresad {
static class Zs{
public void get(){
}
}
static class Ls{
public void get(){
}
}
public static class ThreadDeadlock implements Runnable{
private static Zs zs = new Zs();
private static Ls ls = new Ls();
private boolean flag = false;
@Override
public void run() {
if(flag){
synchronized (zs){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (zs){
zs.get();
}
}
}else{
synchronized (ls){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (ls){
ls.get();
}
}
}
}
}
public static void main(String[] args){
ThreadDeadlock tdl1 = new ThreadDeadlock();
ThreadDeadlock tdl2 = new ThreadDeadlock();
tdl1.flag = true;
tdl2.flag = false;
Thread td = new Thread(tdl1);
Thread td2 = new Thread(tdl2);
td.start();
td2.start();
}
}