Home > Back-end >  Java thread, the problem of the tortoise and the hare.
Java thread, the problem of the tortoise and the hare.

Time:10-23

Write a JAVA application, in the main thread to create two threads, requirements through four states: new, running, terminal and death,

CodePudding user response:

/*
* to simulate the tortoise and the hare
*/
Public class Racer implements Runnable {
Private static String winner;//the winner
@ Override
Public void the run () {
The test ();
}
Public void test () {

For (int steps=1; Steps<=100; Steps++) {
//simulation rest
If (Thread. CurrentThread (). The getName () equals (" rabbit ") & amp; & 10 steps %==0) {
Try {
Thread.sleep(100);
{} catch InterruptedException (e)

e.printStackTrace();
}
}
System. Out.println (Thread. CurrentThread (). The getName () + "- & gt;" + steps);
//whether the game end
A Boolean flag=gameOver (steps);
If (flag) {
break;
}
}

}
Private Boolean gameOver (int steps) {
If (winner!=null) {//winner
return true;
} else {
If (steps==100) {
Winner=Thread. CurrentThread (). The getName ();
System. Out.println (" winner==& gt;" + winner);
return true;
}
}
return false;
}

Public static void main (String [] args) {
Racer Racer=new Racer ();
New Thread (racer, "tortoise"). The start ();
New Thread (racer, "rabbit"). The start ();
}
}

CodePudding user response:

How are new examples pei
  • Related