用线程解决简单的两车相遇

有两辆车,一辆从左往右开,一辆从右往左开,有一条路,长333千米
第一辆左向右开的车每小时行驶60千米,第二辆从右向左的每小时行驶

38千米。问在这条路上,多长时间两车相遇(以每秒模拟每小时)


public class TestMain {
    public static void main(String[] args) throws InterruptedException {
        LeftCar leftcar = new LeftCar();
        RightThread rightcar = new RightThread();
        leftcar.start();
        rightcar.start();
        while(true){
            
            int dis = leftcar.speed*leftcar.times+rightcar.speed*rightcar.times;
        
            if (dis>333) {
                System.out.println("会车了,用了"+rightcar.times+"秒");
                System.exit(0);
            }            
            Thread.sleep(500);
            
        }
    }
}

public class LeftCar extends Thread{
    public int speed = 60;
    public int times =0;
    @Override
    public void run() {
        while (true){
            
            times++;
            System.out.println("左车行驶了"+speed*times);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
      }    
    
    }
}

public class RightThread extends Thread{
    public int speed = 38;
    public int times =0;
    
    @Override
    public void run() {
        while(true){
            times++;
            System.out.println("右车行驶了"+speed*times);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值