运用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();
}
}