运用java中的wait和notifyAll方法模拟玩家等待游戏进入场景

运用java中的wait和notifyAll方法模拟玩家等待游戏进入场景

package com.company;
import java.util.Random;
/**
 * 利用线程中的 wait() 和 notifyAll方法 来实现英雄联盟进入游戏场景
 */
public class ThreadTest implements  Runnable{
    private int count;
    private Random rand =  new Random();
    @Override
    public void run() {
       synchronized (this) {
           int a = rand.nextInt(6);
           try {
               Thread.sleep(a*1000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           count++;
               if (count < 5) {
                   try {
                       System.out.println(Thread.currentThread().getName() + "就绪,等待其他英雄");
                       this.wait();//将当前线程 阻塞,放入线程等待池中。
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               } else {
                   if (count == 5) {
                       System.out.println(Thread.currentThread().getName() + "就绪,英雄到齐3秒后进入战场");
                   }
                   for(int i = 1;i <= 3;i++){
                       System.out.println(i+"秒");
                       try {
                           Thread.sleep(1000);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                   this.notifyAll();//英雄都到齐 释放线程池中所有等待的线程
               }
           System.out.println(Thread.currentThread().getName() + "进入游戏中");
       }
    }
    public static  void main (String arg []) {
        ThreadTest a = new ThreadTest();
        Thread test = new Thread(a,"德玛西亚");
        Thread test2 = new Thread(a,"盲僧");
        Thread test3 = new Thread(a,"火男");
        Thread test4 = new Thread(a,"蛇女");
        Thread test5 = new Thread(a,"小丑");
        test.start();
        test2.start();
        test3.start();
        test4.start();
        test5.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值