Java多线程

来源:互联网 发布:淘宝宝贝分类 编辑:程序博客网 时间:2024/06/06 05:36
题目要求: 

设计一个龟兔赛跑游戏,赛程长度为10歩,每经过一秒,乌龟前进一步,兔子则可能前进两歩也有可能睡觉。

 首先是单线程

public class TortoiseHareRace {public static void main(String[] args) {// TODO Auto-generated method stubboolean[] flags={true,false};        int totalStep=10;   //总的步数        int tortoise =0;    //乌龟的步数        int hareStep=0;     //兔子的步数        System.out.println("龟兔赛跑开始");        while(tortoise<totalStep&&hareStep<totalStep){        tortoise++;        System.out.println("乌龟前进的一步,一共走了 "+ tortoise+"步");//用随机数判断兔子是否前进或者睡觉                boolean isHareSleep= flags[(int)(Math.random()*10)%2];        if(isHareSleep){        hareStep+=2;        System.out.println("兔子跑了 "+hareStep+"步");        }        }}}
显示(随机)

龟兔赛跑开始
乌龟前进的一步,一共走了 1步
兔子跑了 2步
乌龟前进的一步,一共走了 2步
兔子跑了 4步
乌龟前进的一步,一共走了 3步
兔子跑了 6步
乌龟前进的一步,一共走了 4步
兔子跑了 8步
乌龟前进的一步,一共走了 5步
乌龟前进的一步,一共走了 6步
乌龟前进的一步,一共走了 7步
兔子跑了 10步


多线程的实现

乌龟

public class Tortoise implements Runnable {private int totalStep;private int step;public  Tortoise(int totalStep) {this.totalStep=totalStep;}@Overridepublic void run() {// TODO Auto-generated method stub        while (step<totalStep){        step++;        System.out.printf("乌龟跑了%d步\n",step);                }}}

兔子

public class Hare implements Runnable {private boolean[] flags={true,false};    private int totalStep;    private int step;public Hare(int totalStep) {this.totalStep=totalStep;// TODO Auto-generated constructor stub}public void run() {// TODO Auto-generated method stub      while (step<totalStep){      boolean isHareSleep=flags[((int)(Math.random()*10))%2];          if(isHareSleep){          System.out.println("兔子睡着了");}          else{          step+=2;          System.out.println("兔子跑了"+step+"步");          }                }}}

Main函数
public class TortoiseHareRace2 {public static void main(String[] args) {// TODO Auto-generated method stubTortoise tortoise=new Tortoise(10);Hare hare=new Hare(10);Thread tortoisethread =new Thread(tortoise);Thread harethread=new Thread(hare);tortoisethread.start();harethread.start();}}


2 0
原创粉丝点击