Java 多線程練習:模擬多人爬山


需求:

 

 

分析需求:

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()+"到達終點!");
    }
}
ClimbThread
 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 }
Test 模擬多人爬山

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM