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

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

新创一个类

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){   //已经存在胜利者了,则返回true            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();    }

运行结果

在这里插入图片描述

在这里插入图片描述

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

你可能感兴趣的文章
mysql中cast() 和convert()的用法讲解
查看>>
mysql中datetime与timestamp类型有什么区别
查看>>
mysql中floor函数的作用是什么?
查看>>
MySQL中group by 与 order by 一起使用排序问题
查看>>
mysql中having的用法
查看>>
MySQL中interactive_timeout和wait_timeout的区别
查看>>
mysql中int、bigint、smallint 和 tinyint的区别、char和varchar的区别详细介绍
查看>>
mysql中json_extract的使用方法
查看>>
mysql中json_extract的使用方法
查看>>
mysql中null和空字符串的区别与问题!
查看>>
MySQL中ON DUPLICATE KEY UPDATE的介绍与使用、批量更新、存在即更新不存在则插入
查看>>
MYSQL中TINYINT的取值范围
查看>>
Mysql中varchar类型数字排序不对踩坑记录
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
MySQL中地理位置数据扩展geometry的使用心得
查看>>
Mysql中存储引擎简介、修改、查询、选择
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
MySql中的concat()相关函数
查看>>