java实现龟兔百米赛跑程序

来源:互联网 发布:网络体系结构是指 编辑:程序博客网 时间:2024/06/11 19:45
package testThread;import java.util.Random;class tuzi implements  Runnable {    public volatile boolean exit = false;     public void run() {     int run = 0;     for(int i=0;i<15;i++){         while(!exit){        try {            Thread.sleep((int)(Math.random() * 1000));        } catch (InterruptedException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }        Random rand = new Random();        int randNum = rand.nextInt(20);        run = run+randNum;        System.out.println(Thread.currentThread().getName()+"跑了"+run+"米");    if(run>100){        exit = true;         System.out.println("兔子跑到终点了");    }    }}}}class wugui implements  Runnable {    public volatile boolean exit = false;     public void run() {     int run = 0;     for(int i=0;i<40;i++){         while(!exit){        try {            Thread.sleep((int)(Math.random() * 100));        } catch (InterruptedException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }        Random rand = new Random();        int randNum = rand.nextInt(6);        run = run+randNum;        System.out.println(Thread.currentThread().getName()+"跑了"+run+"米");    if(run>100){        exit = true;         System.out.println("乌龟跑到终点了");    }    }}}}public class Thread6 {    public static void main(String[] args) {        // TODO 自动生成的方法存根        new Thread(new tuzi(),"兔子").start();        new Thread(new tuzi()).setPriority(Thread.MIN_PRIORITY);        new Thread(new wugui(),"乌龟").start();    }}
0 0