美文网首页
java笔记--死锁

java笔记--死锁

作者: 吃饱喝足搬代码丶 | 来源:发表于2018-04-09 22:06 被阅读0次

    死锁:

    常见情景之一:同步的嵌套 :(面试的时候可能直接让写)

    class Ticket implements Runnable
    {
        private int num=100;
        Object obj=new Object();
        boolean flag=true;
        
        public void run(){
            if(flag){
                while(true){
                    synchronized(obj){//【这里是拿obj
                        show();       //想进this】
                    }
                }
            }
            else{
                while(true){
                    this.show();//(这里是拿this
                }
            }
        }
            public synchronized void show(){
                synchronized(obj){//想进obj)
                if(num>0){
                    try{
                        Thread.sleep(10);
                    }catch(InterruptedException e){
                    }
                    System.out.println(Thread.currentThread().getName()+"...func..."+num--);
                    }   
                }
            }
        }
    public class DeadLock {
    
        public static void main(String[] args) {
            
            Ticket t=new Ticket();
            
            Thread t1=new Thread(t);
            Thread t2=new Thread(t);
            t1.start();
            try{
                Thread.sleep(10);//先暂停主线程
                }catch(InterruptedException e){}
            t.flag=false;
            t2.start();
        }
    }
    
    运行:
    class Test implements Runnable{
        private boolean flag;
        Test(boolean flag){
            this.flag=flag;
        }
        public void run(){
            if(flag){
                while(true)
                    synchronized(MyLock.locka){
                        System.out.println("if....lockAAAAAA");
                        synchronized(MyLock.lockb){
                            System.out.println("if.....lockBBBBB");
                    }
                }
        }
        else{
            while(true)
                synchronized(MyLock.lockb){
                    System.out.println("else...lockBBBB");
                    synchronized(MyLock.locka){
                        System.out.println("else.....lockAAAA");
                        }
                    }
            }
        }
    }
    class MyLock{
        public static final Object locka=new Object();
        public static final Object lockb=new Object();
    }
    class DeadLock
    {
        public static void main(String[] args){
            Test a=new Test(true);//因为只有ture和false两个值,
            Test b=new Test(false);//所以这里可以创建两个对象
            
            Thread t1=new Thread(a);
            Thread t2=new Thread(b);
            t1.start();
            t2.start();
        }
    }
    
    运行:

    相关文章

      网友评论

          本文标题:java笔记--死锁

          本文链接:https://www.haomeiwen.com/subject/qrswhftx.html