Parameters for the snail:
Every second of the snail speed 0 ~ 1 m
Parameters for the toad:
Every 1.5 seconds toad mobile 0 ~ 2 m
Every mobile output snail | toad ran out of the how many meters, if run in the 100 meters, the output snail | toad ran the 100 meters
CodePudding user response:
import Java. Util. Concurrent. Callable.
Import the Java. Util. Concurrent. TimeUnit;
Public class MyThread extends Thread implements Runnable {
private String name;
Private volatile double sum=0;
Public MyThread (String name) {
this.name=name;
}
Public void the run () {
While (true) {
If (name=="flog" & amp; & Sum<100) {
Double short=Math. The random () * 2;
The sum +=short;
System. Out. Println (" toad walked "+ sum," m ");
Try {
TimeUnit. MILLISECONDS. Sleep (1500);
{} catch InterruptedException (e)
//TODO Auto - generated the catch block,
e.printStackTrace();
}
If (sum> {
=100)System. The out. Println (" toad ran 100 meters ");
}
} else if (name=="q" & amp; & Sum<100) {
Double short=Math. The random ();
The sum +=short;
System. Out. Println (" snail go "+ sum," m ");
Try {
TimeUnit. SECONDS. Sleep (1);
{} catch InterruptedException (e)
//TODO Auto - generated the catch block,
e.printStackTrace();
}
If (sum> {
=100)System. The out. Println (ran 100 meters to the "snail");
}
} else {
return;
}
}
}
Public static void main (String [] args) {
New MyThread (" q "). The start ();
New MyThread (" flog "). The start ();
}
}
CodePudding user response:
import Java. Util. ArrayList;
import java.util.List;
Public class RaceGame {
Public static void main (String [] args) {
GamePlayer GamePlayer=new GamePlayer ();
GamePlayer. AddAnimal (new Animal (" snail ", 1.00));
GamePlayer. AddAnimal (new Animal (2.00) "toad,");
GamePlayer. Start ();
Try {
GamePlayer. The join ();
{} catch InterruptedException (e)
e.printStackTrace();
}
;
}
}
The class GamePlayer extends Thread {
Private ListAnimalList;
Private Boolean gameover=false;
Public GamePlayer () {
AnimalList=new ArrayList(a);
}
Public void addAnimal (Animal Animal) {
This. AnimalList. Add (animal);
}
Public void the run () {
while (! Gameover) {
For (Animal Animal: animalList) {
Animal. The move ();
System. The out. Println (animal. The getName () + "ran" + animal. The getDistance () + "m");
If (animal. GetDistance () & gt; 100) {
System. Out.println (animal getName () + "win!!! ");
Gameover=true;
}
}
}
}
}
The class Animal {
Public Animal (String name, double maxSpeed) {
this.name=name;
Enclosing maxSpeed=maxSpeed;
}
private String name;
Private double maxSpeed=0;
Private double short=0;
Public String getName () {
Return this. The name;
}
Public void move () {
Double temp=Math. The random () * maxSpeed;
Short +=temp;
}
Public double getDistance () {
Return this. Short;
}
}
CodePudding user response:
The