简单死锁代码(java)版

``作为一个菜鸟之前在一些公司里会有死锁代码书写的要求,这里有非常简单的代码展示,首先你要懂得什么是死锁,如下

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();
    }
}


发布了3 篇原创文章 · 获赞 0 · 访问量 23

猜你喜欢

转载自blog.csdn.net/qq_38829655/article/details/105023531
今日推荐