Java多线程——模拟龟兔赛跑的场景

题目分析

1. 编写龟兔赛跑多线程程序,设赛跑长度为100米,先完成的一方胜利。

2. 兔子要休眠一段时间,但是跑步速度更快,乌龟不休眠,但是速度慢.

3. 编写兔子和乌龟类 RabbitAndTurtle继承Thread.然后编写逻辑.

4. 使用Thread的sleep(long milis)方法使线程休眠来控制兔子休眠时间.

5. 用Math.random()方法或setPriority控制双方线优先度.模拟比赛过程.

具体实现

RabbitAndTurtle类

package mydemo.thread;

public class RabbitAndTurtle extends Thread {

    public RabbitAndTurtle(String name) {
        super(name);
    }

    public final int distance = 100;
    static boolean flag = true;
    public int predistance = 0;

    @Override
    public void run() {

        double ran = Math.random();
        String name = Thread.currentThread().getName();
        while (flag) {
            try {
                Thread.sleep(100);//意为让当前线程休眠0.1秒。(龟兔跑完一次等待0.1秒)
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (name.equals("乌龟")) {
                if (Math.random() < 1) {
                    predistance += 1;
                    System.out.println(name + "跑了:" + predistance + "米");
                    if (predistance == distance) {
                        System.out.println("***************乌龟赢了***************");
                        flag = false;
                        break;
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (name.equals("小兔子")) {
                if (Math.random() < 0.7) {
                    predistance += 2;
                    System.out.println(name + "跑了:" + predistance + "米");
                    if (predistance == distance) {
                        System.out.println("***************小兔子赢了***************");
                        flag = false;
                        break;
                    }
                }
                try {
                    Thread.sleep(200);  //兔子休眠时间是乌龟的两倍
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }

    }
}

Race

public class Race {
    public static void main(String[] args) {
        RabbitAndTurtle rabbit = new RabbitAndTurtle("小兔子");
        RabbitAndTurtle turtle = new RabbitAndTurtle("乌龟");
        rabbit.start();
        turtle.start();
    }
}

输出:

······
乌龟跑了:97米
乌龟跑了:98米
小兔子跑了:94米
乌龟跑了:99米
乌龟跑了:100米
***************乌龟赢了***************

 

你可能感兴趣的:(Java,Thread,多线程龟兔赛跑,Java多线程)