多线程之死锁

* 死锁:常见情景之一:同步的嵌套
 * @author 罗摩衔那
 *
 */
class Ticketeds implements Runnable
{
    private int num=100;
    Object obj=new Object();
    boolean flag=true;
    
    public  void run()
    { 
        if(flag)
        while(true)
       {
           ① synchronized (obj)//同步代码块,随意对象锁
            {
                show();
            }
        }
        else
            while(true)
            this.show();    
    }
    ②public synchronized void show()//函数代码块,this
    {    ③synchronized(obj) 
        {    
         if(num>0)
          {
            try {Thread.sleep(10);}catch(InterruptedException e) {}
            System.out.println(Thread.currentThread().getName()+"...function..."+num--);
          }        
    }
}
 public class Deadlock {
     public static void main(String[] args) {
         Ticketeds t=new Ticketeds();
            
            Thread t1=new Thread(t);
            Thread t2=new Thread(t);
            
            t1.start();
            try{Thread.sleep(10);}catch(InterruptedException e) {}
            t.flag=false;
            t2.start();
        }
}

假设线程0依次进入①、②、③,此时线程1依次进入①、②时,线程0想出来,而线程1想进去,就会出现死锁现象.


class Tested implements Runnable
{
    private boolean flag;
    Tested(boolean flag)//写一个有参构造控制布尔值
    {
        this.flag=flag;
    }
    public void 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
 {
     public static final Object locka=new Object();
     public static final Object lockb=new Object();
     
 }
public class DeadlockTest {
public static void main(String[] args) {
    Tested a=new Tested(true);//创建了两个不同的对象那么就是两个独立的任务
    Tested b=new Tested(false);//赋予不同的布尔值-->执行路线true-if/flase-else
    
    Thread t1=new Thread(a);
    Thread t2=new Thread(b);
    
    t1.start();
    t2.start();
}
}

当线程0拿到了locka对象,线程1拿到了lockb对象,出现了死锁

猜你喜欢

转载自www.cnblogs.com/zjm1999/p/9925998.html