| - demand explanation
| - realization of ideas
| - Content Code
. 1 Package cn.thread2; 2 . 3 / ** . 4 * 9527 :: @auther . 5 * @Description: climbing . 6 * @program: shi_yong . 7 * @Create: 2019-08-05 15:41 . 8 * / . 9 public class Hiking the implements the Runnable { 10 // set two properties used to initialize the data . 11 Private int Time; 12 is Private int NUM; 13 is 14 public Hiking ( int Time, int NUM) { 15 the this .time = time; 16 this.num = num; 17 } 18 19 public Hiking() { 20 } 21 22 public int getTime() { 23 return time; 24 } 25 26 public void setTime(int time) { 27 this.time = time; 28 } 29 30 public int getNum() { 31 return num; 32 } 33 34 public void setNum ( int NUM) { 35 the this .num = NUM; 36 } 37 [ 38 is @Override 39 public void () {RUN 40 // Causes num -1 is the cycle of the program termination condition is zero, so the actual number of cycles is +. 1 NUM 41 is for ( int I =-NUM. 1; I> = 0; i-- ) { 42 is the Thread T = Thread.currentThread (); 43 is 44 is // set loop terminates if the termination condition ----, it out this method 45 IF (I == 0 ) { 46 is System.out.println (t.getName () + "has reached the end of"); 47 return ; 48 } 49 // request output message 50 System.out.println (t.getName () + "climbed the first" + (num - i) + " th 100 m" ); 51 is the try { 52 // set simulated climbing sleep unit time takes a little longer it takes the elderly, young takes shorter 53 is the Thread.sleep (time); 54 is } the catch (InterruptedException E) { 55 e.printStackTrace (); 56 is } 57 is 58 } 59 } 60 61 is }
. 1 Package cn.thread2; 2 . 3 / ** . 4 * 9527 :: @auther . 5 * @Description: test class . 6 * @program: shi_yong . 7 * @Create: 2019-08-05 15:52 . 8 * / . 9 public class {the Test 10 public static void main (String [] args) { . 11 // passaged by reference constructor, a 100 m young climbed 50 ms, 100 ms elderly climbed a 100 m 12 // total climb 5 100 m 13 is Hiking Old = new new Hiking (100, 5 ); 14 Hiking = Young new new Hiking (50,5); 15 // provided a elderly 16 the Thread Oldman = new new the Thread (Old, "elderly" ); 17 // provided a young 18 is the Thread YOUNGMAN = new new the Thread (Young, "young" ); . 19 oldMan.start (); 20 is youngMan.start (); 21 is } 22 is }
| - operating results
| - problems in the process of
Running time, we found the problem illustrated below, there is no display has reached the end **
If found by investigation of conditions for loop and is not bound to the for loop, resulting in the body if the method is not performed, as illustrated, the termination condition of i is 1, if the determination condition is i == 0; i = So method body = 0 will not be executed
After i> 0, is changed to i> = 0, the program running