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

来源:互联网 发布:买手机淘宝注册账号 编辑:程序博客网 时间:2024/06/01 08:24

运用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