闲来无事巩固基础
package com.chen.runable;public class Race implements Runnable { private static String winner; @Override public void run() { for (int i = 1; i <= 200; i++) { //模拟兔子睡觉10步一睡 if (Thread.currentThread().getName().equals( "兔子" ) && i%100==0){ try { Thread.sleep( 200 ); } catch (InterruptedException e) { e.printStackTrace(); } } boolean flag = GameOver( i ); if (flag){ break; } System.out.println( Thread.currentThread().getName()+"跑了"+i+"步" ); } } //判断是否跑完 boolean GameOver(int stap){ if (winner!=null){ System.out.println( "比赛已经决出胜负" ); return true; }{ if (stap> =100){ winner = Thread.currentThread().getName(); System.out.println( "胜利者是"+winner ); return true; }else { return false; } } } public static void main(String[] args) { Race race = new Race(); new Thread( race,"乌龟" ).start(); new Thread( race,"兔子" ).start(); }}
运行结果如下所示:(这不是历史的巧合)