模拟接力赛跑

Posted baichang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模拟接力赛跑相关的知识,希望对你有一定的参考价值。

 1 package demo7;
 2 
 3 //模拟接力赛跑,5个人每人跑200米,规定每人跑100米后换下个选手,每跑10米显示信息
 4 public class MyThread6 implements Runnable{
 5     private int count;
 6     
 7     public void run() {
 8         int i=0;
 9         while(i<2) {
10             running();
11             try {
12                 Thread.sleep(500);
13             } catch (InterruptedException e) {
14                 e.printStackTrace();
15             }
16             i++;
17         }
18     }
19     
20     public synchronized void running() {
21         
22         System.out.println(Thread.currentThread().getName()+"拿到接力棒!");
23             for (int j = 0; j <10; j++) {
24                 count+=10;
25                 try {
26                     Thread.sleep(200);
27                 } catch (InterruptedException e) {
28                     e.printStackTrace();
29                 }
30                 System.out.println("跑"+count+"米的选手是---"+Thread.currentThread().getName());
31             }
32         
33         
34     }
35 }
 1 package demo7;
 2 
 3 public class Test6 {
 4     public static void main(String[] args) {
 5         MyThread6 mt = new MyThread6();
 6         
 7         Thread t1 = new Thread(mt,"1号");
 8         Thread t2 = new Thread(mt,"2号");
 9         Thread t3 = new Thread(mt,"3号");
10         Thread t4 = new Thread(mt,"4号");
11         Thread t5 = new Thread(mt,"5号");
12         t1.start();
13         t2.start();
14         t3.start();
15         t4.start();
16         t5.start();
17 
18 
19     }
20 }

 

以上是关于模拟接力赛跑的主要内容,如果未能解决你的问题,请参考以下文章

Java编程题:三线程接力

Java多线程 模拟龟兔赛跑

java--龟兔赛跑模拟

java--龟兔赛跑模拟

多线程模拟龟兔赛跑游戏

多线程模拟龟兔赛跑游戏