public class Solution {
public static void main(String[] args) throws InterruptedException {
OnlineGame onlineGame = new OnlineGame();
onlineGame.start();
}
public static class OnlineGame extends Thread {
public static volatile boolean isWinnerFound = false;
public static List<String> actions = new ArrayList<>();
static {
actions.add("开始游戏");
actions.add("收集资源");
actions.add("增长经济");
actions.add("杀死敌人");
}
protected Gamer gamer1 = new Gamer("史密斯", 3);
protected Gamer gamer2 = new Gamer("琼斯", 1);
protected Gamer gamer3 = new Gamer("盖茨", 5);
public void run() {
gamer1.start();
gamer2.start();
gamer3.start();
while (!isWinnerFound) {
}
gamer1.interrupt();
gamer2.interrupt();
gamer3.interrupt();
}
}
public static class Gamer extends Thread {
private int rating;
public Gamer(String name, int rating) {
super(name);
this.rating = rating;
}
@Override
public void run() {
//在此编写你的代码
int i = 0;
try {
while (i < OnlineGame.actions.size()){
System.out.println(getName() + ": " + OnlineGame.actions.get(i));
i++;
Thread.sleep((long) (1000 / rating));
}
if (!OnlineGame.isWinnerFound){
OnlineGame.isWinnerFound = true;
System.out.println(getName() + ": 赢了!");
}
} catch (InterruptedException e) {
System.out.println(getName() + ": 失败");
}
}
}
}
我不太能理解有下滑线的那段代码。在while循环里面调用interrupt(),全部玩家不都应该打印失败么?因为玩家的run()方法里都有sleep(),再调用interrupt()就会有异常才对不是么?
已解决
评论 (4)
- 受欢迎
- 新
- 旧
你必须先登录才能发表评论
Thomas
23 九月 2021, 09:50解决方法
maybe try it this way... so it is easier to understand
The winner, the first to leave the while loop, sets the isWinnerFound boolean to true, then the remaining players get interrupted cause
while (!isWinnerFound) {
}
this loop in main ends. Then the interrupted flags of all players get set. This just has an effect for the remaining ones (losers) as the winner thread already is ended and there's no more sleep method or isInterrupted() check.
The looser threads end up in the catch block where the lost message gets printed. +2
leeway
24 九月 2021, 04:28
赢家为什么能跑出while循环?游戏线程内调用玩家线程的interrupt(),而玩家线程中又有sleep(),
这种情况下所有玩家不都会被中断么? 0
leeway
24 九月 2021, 04:35
当玩家线程调用slee()方法时,玩家线程处于阻塞状态。然后游戏线程在循环调用玩家线程的interrupt()方法,这个时候就应该抛出中断线程才对吧?
0
leeway
24 九月 2021, 04:44
啊,我找到问题所在了,是我太蠢,看差了代码
这个while循环并没有把interrupt()给包括进去 这个循环里它什么都没做,作用就是等待赢家出现,然后打断其他线程。是我看代码太不仔细了。不管怎样,谢谢你的回复 0