欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程——龟兔赛跑Runnable接口

程序员文章站 2022-05-02 10:09:12
...

多线程——龟兔赛跑Runnable接口

package thread;

public class competition implements Runnable{
    private static String contest;
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("Rabbit ")){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (Thread.currentThread().getName().equals("Tortoise ")){
                try {
                    Thread.sleep(95);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean end = endGame(i);
            if (end){
                break;
            }
            System.out.println(Thread.currentThread().getName()+" ran "+i+" steps.");
        }
    }

    private boolean  endGame(int steps){
        if (contest!=null){
            return true;
        }
        if (steps>=100){
            contest = Thread.currentThread().getName();
            System.out.println("contest is "+contest);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        competition competition = new competition();

        new Thread(competition,"Rabbit ").start();
        new Thread(competition,"Tortoise ").start();
    }
}

https://www.bilibili.com/video/BV1V4411p7EF?p=7

相关标签: 多线程 java