博客
关于我
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/

你可能感兴趣的文章
Python web自动化测试 —— 文件上传
查看>>
python win32api键盘_Python win32api.keybd_event模拟键盘输入
查看>>
python Workbook 表格宽度
查看>>
python 中 dict 的另一种用法
查看>>
Python 中只有一个 True 和一个 False 对象吗?
查看>>
Python 中多线程与多处理之间的区别
查看>>
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>
Python 优化提速的 8 个小技巧
查看>>
Python 余弦相似度与皮尔逊相关系数 计算
查看>>
python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
查看>>
python 使用filetype校验文件
查看>>
Python 使用flush函数将缓冲区数据立即写磁盘
查看>>
python 使用in判断不准确,in不好使
查看>>
Python 使用pandas 进行查询和统计详解
查看>>
Redis 配置文件redis.conf详细解释
查看>>
python网络爬虫(2)——scrapy框架的基础使用
查看>>
Python 使用哈希函数用于加密
查看>>
Python 依赖管理的革新——Poetry 深度解析
查看>>