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

来源:互联网 发布:科尔盖特大学 知乎 编辑:程序博客网 时间:2024/06/06 07:04
有两辆车,一辆从左往右开,一辆从右往左开,有一条路,长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();
            }
        }
    }
}


原创粉丝点击