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 模拟多人爬山

运行结果:

 

posted @ 2019-08-06 16:03  靖凯  阅读(1755)  评论(0编辑  收藏  举报