博客
关于我
java多线程(5)——龟兔赛跑程序
阅读量:333 次
发布时间:2019-03-04

本文共 1238 字,大约阅读时间需要 4 分钟。

新创一个类

public class Race implements Runnable {    private static String winner;    @Override    public void run() {        for (int i = 1; i <= 100; i++) {            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            if (gameOver(i)) {                break;            }            System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");        }    }    private boolean gameOver(int steps) {        if (winner != null) {            return true;        }        if (steps >= 100) {            winner = Thread.currentThread().getName();            System.out.println("winner is "+winner);            return true;        }        return false;    }}

运行

public static void main(String[] args) {    Race race = new Race();    new Thread(race,"兔子").start();    new Thread(race,"乌龟").start();}

运行结果

通过代码实现了一个简单的赛跑逻辑,两个参与者分别是"兔子"和"乌龟"。在运行过程中,兔子每跑完10步会暂停10毫秒,而乌龟则一直保持稳定的速度。最终的胜利者将通过`gameOver`方法自动判定,当某个参与者完成全部步数或首先完成比赛时,游戏将结束。

在实际运行中,乌龟通常会比兔子先完成比赛,因为兔子需要定期暂停,增加了额外的时间消耗。通过这种方式,可以直观地观察到不同参与者的速度差异以及暂停策略对最终结果的影响。

转载地址:http://nieq.baihongyu.com/

你可能感兴趣的文章
Nokia5233手机和我装的几个symbian V5手机软件
查看>>
Non-final field ‘code‘ in enum StateEnum‘
查看>>
none 和 host 网络的适用场景 - 每天5分钟玩转 Docker 容器技术(31)
查看>>
None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
查看>>
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NoSQL介绍
查看>>
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>