本文主要是介绍龟兔赛跑!!!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
让我们来用线程的知识模拟一个有趣的龟兔赛跑游戏。
比赛规则
兔子与乌龟一起跑,每次步长都一样,兔子每跑40步就睡一会,谁先跑到100步,就获得胜利!
Runnable实现
public class Racer implements Runnable{private String winner; //胜利者public static void main(String[] args) {Racer racer = new Racer();new Thread(racer,"乌龟").start();new Thread(racer,"兔子").start();}//重写run方法public void run(){for(int steps=1;steps<=100;steps++){//让兔子睡觉if(Thread.currentThread().getName().equals("兔子")&&steps%40==0){try {Thread.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName()+"-->"+steps);//判断比赛是否结束boolean flag = gameOver(steps);if(flag) break;}}public boolean gameOver(int steps){if(winner!=null) return true; //健壮性else{if(steps==100){ //谁跑到100步,游戏就结束winner = Thread.currentThread().getName();System.out.println("winner is:"+winner);return true;}}return false;}
}
最终结果
Callable实现
public class Racer2 implements Callable<Integer>{private String winner; //胜利者public static void main(String[] args) throws InterruptedException, ExecutionException {//1、创建目标对象: Racer2 racer = new Racer2();//2、创建执行服务: ExecutorService ser = Executors.newFixedThreadPool(2);//3、提交执行: Future<Integer> result1 = ser.submit(racer);Future<Integer> result2 = ser.submit(racer);//4、获取结果: Integer r1 =result1.get();Integer r2 =result2.get();System.out.println(r1+"-->"+r2);//5、关闭服务:ser.shutdownNow();}//重写run方法public Integer call() throws InterruptedException{for(int steps=1;steps<=100;steps++){//让兔子睡觉if(Thread.currentThread().getName().equals("pool-1-thread-1")&&steps%40==0){Thread.sleep(5);}System.out.println(Thread.currentThread().getName()+"-->"+steps);//判断比赛是否结束boolean flag = gameOver(steps);if(flag) return steps;}return null;}public boolean gameOver(int steps){if(winner!=null) return true; //健壮性else{if(steps==100){ //谁跑到100步,游戏就结束winner = Thread.currentThread().getName();if(winner.equals("pool-1-thread-1")) System.out.println("winner is:兔子");else System.out.println("winner is:乌龟");return true;}}return false;}
}
分析
以上是两份不同方式实现的完整代码,功能很简单,用Thread.sleep() 模拟了兔子睡觉的过程,开启两个线程模拟兔子和乌龟同时赛跑。
这篇关于龟兔赛跑!!!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!