Package Penalty for jd1908_corejava.ch15.work; // thread classic question - hand problems public class Race { public static void main (String [] args) { RabbitAndTurtle The Rabbit = new new RabbitAndTurtle (); rabbit.setName ( "Bunny" ); turtle RabbitAndTurtle = new new RabbitAndTurtle (); turtle.setName ( "turtle" ); rabbit.start (); turtle.start (); } } class RabbitAndTurtle the extends the Thread { Private intNUM; // boolean type default initial value is false Private static boolean Flag; // After the run is finished thread will die, closed // yield (), the release of resources, run back to the top @Override public void run () { the while (NUM <100 ) { IF (In Flag) { // thread termination BREAK ; } IF (Math.random () <0.3 && Thread.currentThread () getName () the equals ( "rabbit.". )) { NUM + = 2 ; System.out.println ( "rabbit run" + NUM); IF(NUM == 100 ) { System.out.println ( "Rabbit win" ); BREAK ; } to Thread.yield (); } IF . (Math.random ()> 0.3 && Thread.currentThread () getName (). equals ( "turtle" )) { NUM + =. 1 ; System.out.println ( "tortoise ran" + NUM); IF (NUM == 100 ) { System.out.println ( "tortoise win" ); BREAK ; } to Thread.yield (); } } if (num == 100) { flag = true; } } }
Note: The two threads are independent, but the flag is shared
Do not have the same type of object is instantiated static resources are shared!