多线程---模拟接力赛跑

 1 //接力赛跑的线程,实现Runnable
 2 public class MyRunnable implements Runnable{
 3     static int num = 10;
 4     private String thread;
 5     Object lock = new Object();
 6     public void run() {
 7         while(true) {
 8             synchronized (lock) {
 9                 if(num == 0) {
10                     System.out.println("比赛结束!");
11                     break;
12                 }
13                 thread = Thread.currentThread().getName();
14                 System.out.println(thread+"拿到了接力棒!");
15                 num--;            
16                 for(int i =1;i<=10;i++) {
17                     try {
18                         Thread.sleep(10);
19                     } catch (InterruptedException e) {
20                         // TODO Auto-generated catch block
21                         e.printStackTrace();
22                     }
23                     System.out.println(thread+"跑了"+(i*10));
24                 }
25                 return;
26             }
27         }
28     }
29 }
接力赛跑的线程,实现Runnable
 1 //测试类
 2 public class Test {
 3     public static void main(String[] args) throws InterruptedException {
 4         MyRunnable m = new MyRunnable();
 5         Thread thread1 = new Thread(m,"1号选手");
 6         Thread thread2 = new Thread(m,"2号选手");
 7         Thread thread3 = new Thread(m,"3号选手");
 8         Thread thread4 = new Thread(m,"4号选手");
 9         Thread thread5 = new Thread(m,"5号选手");
10         Thread thread6 = new Thread(m,"6号选手");
11         Thread thread7 = new Thread(m,"7号选手");
12         Thread thread8 = new Thread(m,"8号选手");
13         Thread thread9 = new Thread(m,"9号选手");
14         Thread thread10 = new Thread(m,"10号选手");
15         thread1.start();
16         thread2.start();
17         thread3.start();
18         thread4.start();
19         thread5.start();
20         thread6.start();
21         thread7.start();
22         thread8.start();
23         thread9.start();
24         thread10.start();
25         
26     }
27 }
测试类

运行结果:

 

 

 

 

问题:无法实现少于十人的接力赛跑,实现不连续出现的情况!

转载于:https://www.cnblogs.com/Dean-0/p/11305128.html

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值