讓烏龜和兔子在同一個賽道從1開始跑到100,看看誰更快.
1 public class Racer implements Runnable{ 2 private static String winner;//勝利者 3 4 @Override 5 public void run() { 6 //賽道 7 for (int step = 1; step <= 100; step++) { 8 /* if(Thread.currentThread().getName().equals("兔子")&&step%50==0){ 9 try { 10 Thread.sleep(200); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 }*/ 15 System.out.println(Thread.currentThread().getName()+"---->走了"+step+"步"); 16 17 boolean flag= GameOver(step); 18 if(flag){ 19 break; 20 } 21 22 } 23 } 24 25 private boolean GameOver(int step) { 26 if(winner!=null){ 27 return true; 28 }else{ 29 if(step==100){ 30 winner=Thread.currentThread().getName(); 31 System.out.println("勝利者是-->"+winner); 32 } 33 } 34 return false; 35 } 36 37 public static void main(String[] args) { 38 Racer racer = new Racer(); 39 new Thread(racer,"兔子").start(); 40 new Thread(racer,"烏龜").start(); 41 42 } 43 44 }
運行結果:
兔子---->走了1步
...................
兔子---->走了98步
兔子---->走了99步
兔子---->走了100步
勝利者是-->兔子
怎么竟然是兔子贏了,可是現實中龜兔賽跑是烏龜贏了,我們加入線程睡眠要是兔子就讓他睡一會,烏龜就可以贏了.
1 public class Racer implements Runnable{ 2 private static String winner;//勝利者 3 4 @Override 5 public void run() { 6 //賽道 7 for (int step = 1; step <= 100; step++) { 8 if(Thread.currentThread().getName().equals("兔子")&&step%50==0){ 9 try { 10 Thread.sleep(200); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 } 15 System.out.println(Thread.currentThread().getName()+"---->走了"+step+"步"); 16 17 boolean flag= GameOver(step); 18 if(flag){ 19 break; 20 } 21 22 } 23 } 24 25 private boolean GameOver(int step) { 26 if(winner!=null){ 27 return true; 28 }else{ 29 if(step==100){ 30 winner=Thread.currentThread().getName(); 31 System.out.println("勝利者是-->"+winner); 32 } 33 } 34 return false; 35 } 36 37 public static void main(String[] args) { 38 Racer racer = new Racer(); 39 new Thread(racer,"兔子").start(); 40 new Thread(racer,"烏龜").start(); 41 42 } 43 44 }
運行結果:
烏龜---->走了96步
烏龜---->走了97步
烏龜---->走了98步
烏龜---->走了99步
烏龜---->走了100步
勝利者是-->烏龜
兔子---->走了50步
這下不管怎么跑都是烏龜贏了.
