编写
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(); } }
运行