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

题目:模拟多人爬山

需求说明:

1、每个线程代表一个人

2、实可设置每人爬山速度

3、每爬完100米显示信息

4、爬到终点时给出相应提示

2.解题思路 为了实现题目需求,我们可以创建两个线程,分别代表年轻人和老年人。每个线程都有自己的爬山速度,并且每爬100米显示信息。当某个线程爬到终点时,给出相应提示。

1、创建线程类GoHill

      属性:爬行的速度speed米每秒,爬行的总路程metre米。

      构造方法完成属性初始化

2、实现run()方法

      线程休眠模拟爬山中的延时

3、实现测试类Test

     创建多个线程对象模拟多个人,设置人名、爬100米时长

  public class Test {
    public static void main(String[] args) {
        GoHill young = new GoHill("年轻人", 20, 300);
        young.start();
        GoHill oldMan = new GoHill("老年人", 10, 300);
        oldMan.start();
      }
  }

4,   线程类

        

public class GoHill extends Thread{
    private String name; // name 爬山人
    private int speed; // speed 爬山人速度
    private int metre; // metre 山的高度

    public GoHill(String name,int speed,int metre){
        this.name = name;
        this.speed = speed;
        this.metre = metre;
    }

    @Override
    public void run() {
        int time = 0;
        int MetreSum = 0;
        while (MetreSum < metre){
            try {
                time++;
                System.out.println("第"+time+"秒");
                MetreSum = time * speed;
                if (MetreSum <= metre){
                    System.out.println(name+"爬山"+MetreSum+"米");
                    if (MetreSum % 100 == 0){
                        System.out.println(name+"爬了"+(MetreSum/100)+"个100米");
                    }
                }
                Thread.sleep(time*100);    //线程休眠来实现爬山的间隔
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值