死锁的演示

死锁

当业务比较复杂时,多线程应用里有可能会发生死锁

演示死锁

  1. 线程一占有对象一,试图占有对象二
  2. 线程二占有对象二,试图占有对象一
  3. 线程一等待线程二释放线程二
  4. 线程二等待线程一释放线程一

练习

package multiThread2;

public class main1 {
   public static void main(String[] args) {
       Animal a1 = new Animal();
       Animal a2 = new Animal();
       Animal a3 = new Animal();
       Thread t1 = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (a1){
                   System.out.println("a1在做饭");
                   try {
                       Thread.sleep(1000);
                   }catch (Exception e){
                       throw new RuntimeException(e);
                   }
                   System.out.println("a1试图干饭");
                   System.out.println("a1等待着");
                   synchronized (a2){
                       System.out.println("a1 doing");
                   }
               }
           }
       });
       t1.start();
       Thread t2 = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (a2){
                   System.out.println("a2在做饭");
                   try {
                       Thread.sleep(1000);
                   }catch (Exception e) {
                       throw new RuntimeException(e);
                   }
                   System.out.println("a2试图干饭");
                   System.out.println("a2等待着");
                   synchronized (a3){
                       System.out.println("a2 doing");
                   }
               }
           }
       });
       t2.start();
       Thread t3 = new Thread(new Runnable() {
           @Override
           public void run() {
               synchronized (a3){
                   System.out.println("a3在做饭");
               }
               try {
                   Thread.sleep(1000);
               }catch (Exception e){
                   throw new RuntimeException(e);
               }
               System.out.println("a3试图干饭");
               System.out.println("a3等待着");
               synchronized (a1){
                   System.out.println("a3 doing");
               }
           }
       });
       t3.start();
   }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值