Java 多线程练习:模拟多人爬山

时间:2022-12-29 18:24:04

需求:

 

Java 多线程练习:模拟多人爬山

 

分析需求:

Java 多线程练习:模拟多人爬山

Java 多线程练习:模拟多人爬山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
Java 多线程练习:模拟多人爬山Java 多线程练习:模拟多人爬山
 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 模拟多人爬山

运行结果:

Java 多线程练习:模拟多人爬山