接力賽跑(多線程,線程安全)


編寫

package com.Thread;

/**
 *     接力賽測試類
 * @author Administrator
 *
 */
public class Running implements Runnable{
    /**
     *     跑步
     */
    public void run(){
        synchronized (this) {    //線程安全:一次只能有一個運動員跑步    必須是同一個線程
            System.out.println(Thread.currentThread().getName()+"接過接力棒");
            for(int i=0;i<10;i++) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"跑了"+(i+1)*10+"米");
            }
        }
    }

/**
 *     測試類
 */
    public static void main(String[] args) {
        Running r=new Running();        //創建線程對象

        Thread a1=new Thread(r,"1號選手");
        Thread a2=new Thread(r,"2號選手");
        Thread a3=new Thread(r,"3號選手");
        Thread a4=new Thread(r,"四號選手");
        Thread a5=new Thread(r,"五號選手");
        Thread a6=new Thread(r,"六號選手");
        Thread a7=new Thread(r,"七號選手");
        Thread a8=new Thread(r,"八號選手");
        Thread a9=new Thread(r,"九號選手");
        Thread a10=new Thread(r,"十號選手");

        a1.start();
        a2.start();
        a3.start();
        a4.start();
        a5.start();
        a6.start();
        a7.start();
        a8.start();
        a9.start();
        a10.start();


    }
}

 

運行

 


免責聲明!

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



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