多人爬山(多線程 )


編寫

 

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;
            }
        }
        
    }
}

 

 

 

運行

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM