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