Java复习 多线程实现简易版龟兔赛跑



/**
 * 模拟龟兔赛跑
 *  * @author liujunwei1016
 *
 */
public class Game implements Runnable {
		private String winner;
		@Override
		public void run() {
			
			for(int steps =1; steps<=100;steps++) {	
                //模拟睡觉
				if(Thread.currentThread().getName().equals("rabbit") && steps%10==0) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			System.out.println(Thread.currentThread().getName()+"-->"+ steps);
			//比赛是否结束
			boolean flag = gameOver(steps);
			if(flag) {
				break;
			}
		}
			
		}
		private boolean  gameOver(int steps) {
			if(winner!=null) {
				return true;
			}else {
				if(steps==100) {	
			winner = Thread.currentThread().getName();
			System.out.println("winner-->"+winner);
			return true;
			}
		}
			return false;
	
		}
		public static void main(String[] args) {
			Game g = new Game();
			new Thread(g,"rabbit").start();
			new Thread(g,"tortoise").start();

	}

}

 

你可能感兴趣的:(java)