|--需求说明
|--实现方式
每个线程跑完return掉
|--代码内容
1 package cn.thread3; 2 3 /** 4 * @auther::9527 5 * @Description: 接力线程类 6 * @program: shi_yong 7 * @create: 2019-08-05 17:03 8 */ 9 public class Relay implements Runnable { 10 private int num = 10; //每个人跑的时候显示的数量 11 private int total = 1000; 12 private int count = 0; //记数 13 private boolean boo = false; 14 15 @Override 16 public synchronized void run() { 17 18 //运行接力赛这个经过线程同步的方法 19 while (!boo) { 20 //如果跑满1000,就告知已经跑满1000米 21 if (total == 0) { 22 System.out.println("已经跑满1000米"); 23 boo = true; 24 break; 25 } 26 //运行接力的方法 27 relay(); 28 total-=100; 29 try { 30 Thread.sleep(500); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 //一个线程跑完要return掉 35 return; 36 } 37 } 38 39 40 public synchronized void relay(){ 41 //如果没跑完就继续跑 42 if (total>0){ 43 String thread = Thread.currentThread().getName(); 44 //按提示输出 45 System.out.println(thread + "拿到了接力棒"); 46 //设定单个选手的跑的变量 47 48 for (int i = 1; i <= num; i++) { 49 System.out.println(Thread.currentThread().getName() + "跑了" + (i * 10) + "米"); 50 count += 10; 51 } 52 } 53 54 } 55 }
1 package cn.thread3; 2 3 /** 4 * @auther::9527 5 * @Description: 程序入口 6 * @program: shi_yong 7 * @create: 2019-08-05 17:06 8 */ 9 public class Test { 10 public static void main(String[] args) { 11 //实例化 线程类 12 Relay relay = new Relay(); 13 //设定10个选手 14 Thread t1 = new Thread(relay,"1号选手"); 15 Thread t2 = new Thread(relay,"2号选手"); 16 Thread t3 = new Thread(relay,"3号选手"); 17 Thread t4 = new Thread(relay,"4号选手"); 18 Thread t5 = new Thread(relay,"5号选手"); 19 Thread t6 = new Thread(relay,"6号选手"); 20 Thread t7 = new Thread(relay,"7号选手"); 21 Thread t8 = new Thread(relay,"8号选手"); 22 Thread t9 = new Thread(relay,"9号选手"); 23 Thread t10 = new Thread(relay,"10号选手"); 24 Thread t11 = new Thread(relay,"11号选手"); 25 //启动线程 26 t1.start(); 27 t2.start(); 28 t3.start(); 29 t4.start(); 30 t5.start(); 31 t6.start(); 32 t7.start(); 33 t8.start(); 34 t9.start(); 35 t10.start(); 36 t11.start(); 37 } 38 }
|--运行结果