多人爬山(多线程 )

编写

 

package com.Input_Output.I_O2;

/**
 *     测试类
 */
class ClimbTest{
    public static void main(String[] args) {
        //创建线程
        ClimbThread t1=new ClimbThread(500,1);
        ClimbThread t2=new ClimbThread(800,1);
        
        //给线程赋名
        t1.setName("□少壮不努力");
        t2.setName("■老大徒伤悲");
        
        //start运行
        t1.start();
        t2.start();
    }
}

/**
 *      爬山对象 线程
 */
class ClimbThread extends Thread{
    int time;                //速度/米
    int num;                //每次休息时间
    int mountain;            //山的高度
    
    public ClimbThread(int time,int mountain) {
        super();
        this.time=time;
        this.mountain = mountain*1000;                    //千米
    }
    //run方法
    public void run() {
        String name=Thread.currentThread().getName();    //获取当前线程名
        while(true) {
            mountain-=100;                                //爬山
            System.out.println(name+"爬了"+(num+1)+"个100米");
            num++;                                        //爬100米次数+1
            try {
                Thread.sleep(time);                        //爬100用的时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(mountain<=0) {
                System.out.println("***"+name+"爬到了终点***");
                break;
            }
        }
        
    }
}

 

 

 

运行

 

posted @ 2019-03-09 13:25  纸灰  阅读(934)  评论(0编辑  收藏  举报