接力赛跑(多线程,线程安全)


编写

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