模拟多人爬山

 1 package com.twod4z;
 2 /**
 3  * @program: com.twod4z
 4  * @description:爬山对象 线程
 5  * @author: Mr.Lin
 6  * @create: 2019年8月7日
 7  **/
 8 public class Climb extends Thread{
 9     int time;                //速度/米
10     int num;                //每次休息时间
11     int mountain;            //山的高度
12     
13     public Climb(int time,int mountain) {
14         super();
15         this.time=time;
16         this.mountain = mountain*1000;                    //千米
17     }
18     //run方法
19     public void run() {
20         String name=Thread.currentThread().getName();    //获取当前线程名
21         while(true) {
22             mountain-=100;                                //爬山
23             System.out.println(name+"爬了"+(num+1)+"个100米");
24             num++;                                        //爬100米次数+1
25             try {
26                 Thread.sleep(time);                        //爬100米用的时间
27             } catch (InterruptedException e) {
28                 e.printStackTrace();
29             }
30             if(mountain<=0) {
31                 System.out.println("***"+name+"爬到了终点***");
32                 break;
33             }
34         }
35         
36     }
37 
38 }
Climb
 1 package com.twod4z;
 2 /**
 3  * @program: com.twod4z
 4  * @description:测试类
 5  * @author: Mr.Lin
 6  * @create: 2019年8月8日
 7  **/
 8 public class ClimbTest {
 9      public static void main(String[] args) {
10             //创建线程
11             Climb t1=new Climb(500,1);
12             Climb t2=new Climb(800,1);
13             
14             //给线程赋名
15             t1.setName("年轻人");
16             t2.setName("!老年人");
17             
18             //start运行
19             t1.start();
20             t2.start();
21         }
22 
23 }
Climb Test

原文地址:https://www.cnblogs.com/lpbk/p/11319177.html