JAVA入门之多线程 龟兔赛跑实例

龟兔赛跑:
赛道1000米,兔子每秒100米,乌龟每秒50米,兔子跑到900米处,自己把自己挂起,乌龟一直跑,乌龟跑到终点 唤醒兔子,最终乌龟获得比赛胜利,兔子比赛失败。
(模拟比赛过程)

Rabit.java

package test3;

public class Rabit  extends  Thread{
     
    private int dist=100;

    public Rabit(int dist) {
     
        this.dist = dist;
    }

    @Override
    public void run() {
     
        for (int i = 0; i <=900 ; i+=dist) {
     
            if (i==800){
     
                System.out.println("兔子睡着了");
                this.suspend();

            }
            try {
     
                Thread.sleep(1000);
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
            System.out.println(this.getName()+"已经跑了"+(i+dist)+"米");
        }
    }
}

WUgui .java

package test3;

public class WUgui  extends  Thread{
     

    //速度50
    private int dist=50;
    private  Rabit rabit;
    public WUgui(String name, int dist,Rabit rabit) {
     
        super(name);
        this.dist = dist;
        this.rabit=rabit;
    }

    @Override
    public void run() {
     
        for (int i = 0; i <950 ; i+=this.dist) {
     
            System.out.println(this.getName()+"已经跑了"+(i+this.dist)+"米");
            try {
     
                Thread.sleep(1000);
            } catch (InterruptedException e) {
     
                e.printStackTrace();
            }
        }
        System.out.println(this.getName()+"已经跑到终点  获得胜利 唤醒兔子");
        this.rabit.resume();
    }
}

Test.java

package test3;

public class Test {
     
    public static void main(String[] args) {
     
        Rabit rabit = new Rabit(100);
        rabit.setName("兔子");
        WUgui wUgui = new WUgui("乌龟",50,rabit);
      //  wUgui.setName("乌龟");

        rabit.start();
        wUgui.start();
    }
}

你可能感兴趣的:(Java基础,多线程)