java线程同步之死锁问题

    技术2022-06-12  50

    问题描述:死锁问题应该是这样发生的。情景:两个人,一个厕所。情节:里面的人办完事了,可是忘了带纸,就给外面的人要纸,外面的人不给,于是乎,出不来;这外面一个人有纸急冲冲的要办事,可是进不去,说里面的人,赶紧出来,可是里面的人没有纸怎么出的来。于是,就这样两个人僵持着。问题的原因在于,里面的人等着外面的人给他纸,外面的人等着里面的人给让位,各自需要的资源被占用了,于是死锁就发生了。

    public class DeadLock implements Runnable{         //设置标识符         public int flag = 1;         //创建两个Object对象         static Object o1 = new Object();         static Object o2 = new Object();         //重写run方法         public void run (){             System.out.println("flag = "+flag);             if(flag == 1){                 //当flag的值为1时,锁定o1,睡眠5ooms,然后执行o2                 synchronized(o1){                     try {                         Thread.sleep(500);                         System.out.println("i am o1");                        }                     catch( Exception e) {                         System.out.println("error!");                     }                                     synchronized(o2){                         System.out.println("o2");                     }                 }             }                         if(flag == 0 ){                 //当flag的值为0时,锁定o2,睡眠5ooms,然后执行o1                 synchronized(o2){                     try {                         Thread.sleep(500);                     System.out.println("i am o2");                                         }                     catch( Exception e) {                         System.out.println("error!");                     }                     synchronized(o1){                         System.out.println("o1");                     }                 }             }         }         public static void main(String args[]){             DeadLock dl1 = new DeadLock();             DeadLock dl2 = new DeadLock();             //为各自对象的标识符赋值             dl1.flag = 0;             dl2.flag = 1;             Thread t1 = new Thread(dl1);             Thread t2 = new Thread(dl2);             //两个线程启动,各自调用run方法,这样的话各自需要的资源被占用,死锁发生             t1.start();             t2.start();         }     }


    最新回复(0)