多線程---模擬接力賽跑


 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 }
測試類

運行結果:

 

 

 

 

問題:無法實現少於十人的接力賽跑,實現不連續出現的情況!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM