需求:
分析需求:

public class ClimbThread extends Thread { private int time; // 爬100米的時間 public int num = 0; // 爬多少個100米 public ClimbThread(String name, int time, int kilometer) { super(name); this.time = time; this.num = kilometer * 1000 / 100; } public void run() { while (num > 0) { try { Thread.sleep(this.time); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "爬完100米!"); num--; } System.out.println(Thread.currentThread().getName()+"到達終點!"); } }

1 /** 2 * 模擬多人爬山 3 */ 4 public class Test { 5 public static void main(String[] args) { 6 ClimbThread youngMan = new ClimbThread("年輕人",500,1); 7 ClimbThread oldMan = new ClimbThread("老年人",1500,1); 8 System.out.println("********開始爬山*********"); 9 youngMan.start(); 10 oldMan.start(); 11 } 12 }
運行結果: