条件が満たされたときにスレッドを停止する方法についていくつか提案をお願いします。
ここに私のコードがあります:
public class Animal implements Runnable {
private static boolean winner = false;
private String name;
private int position;
private int speed;
private long restMax;
public Animal(String name, int position, int speed, long restMax) {
this.name = name;
this.position = position;
this.speed = speed;
this.restMax = restMax;
}
@Override
public void run() {
while (position < 100){
position += speed;
try {
Thread.sleep((long) (0 + (Math.random() * restMax)));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " is at position " + position );
}
if (position >= 100){
winner = true;
System.out.println(name + " is the winner of the race!");
Thread.interrupted();
}
}
}
main メソッドで s を作成した 2 つの Animal オブジェクトの出力を次に示します。
勝者が宣言されたときでさえ、スレッドは続きました (この場合、Homegrown Rabbit が勝者です)。私の質問は、条件が満たされたときに他のスレッドを停止するにはどうすればよいですか? interrupted() メソッドを試しましたが、違いは見られませんでした。
Homegrown Rabbit is at position 5
Homegrown Rabbit is at position 10
Wild Turtle is at position 3
Wild Turtle is at position 6
Homegrown Rabbit is at position 15
Homegrown Rabbit is at position 20
Wild Turtle is at position 9
Wild Turtle is at position 12
Wild Turtle is at position 15
Homegrown Rabbit is at position 25
Wild Turtle is at position 18
Homegrown Rabbit is at position 30
Wild Turtle is at position 21
Homegrown Rabbit is at position 35
Wild Turtle is at position 24
Homegrown Rabbit is at position 40
Wild Turtle is at position 27
Wild Turtle is at position 30
Homegrown Rabbit is at position 45
Homegrown Rabbit is at position 50
Wild Turtle is at position 33
Homegrown Rabbit is at position 55
Wild Turtle is at position 36
Wild Turtle is at position 39
Homegrown Rabbit is at position 60
Wild Turtle is at position 42
Wild Turtle is at position 45
Homegrown Rabbit is at position 65
Wild Turtle is at position 48
Wild Turtle is at position 51
Homegrown Rabbit is at position 70
Homegrown Rabbit is at position 75
Wild Turtle is at position 54
Wild Turtle is at position 57
Wild Turtle is at position 60
Homegrown Rabbit is at position 80
Homegrown Rabbit is at position 85
Wild Turtle is at position 63
Wild Turtle is at position 66
Homegrown Rabbit is at position 90
Wild Turtle is at position 69
Wild Turtle is at position 72
Wild Turtle is at position 75
Homegrown Rabbit is at position 95
Wild Turtle is at position 78
Homegrown Rabbit is at position 100
Homegrown Rabbit is the winner of the race!
Wild Turtle is at position 81
Wild Turtle is at position 84
Wild Turtle is at position 87
Wild Turtle is at position 90
Wild Turtle is at position 93
Wild Turtle is at position 96
Wild Turtle is at position 99
Wild Turtle is at position 102
Wild Turtle is the winner of the race!