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

你可能感兴趣的文章
Netty工作笔记0024---SelectionKey API
查看>>
Netty工作笔记0025---SocketChannel API
查看>>
Netty工作笔记0027---NIO 网络编程应用--群聊系统2--服务器编写2
查看>>
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0057---Netty群聊系统服务端
查看>>
Netty工作笔记0060---Tcp长连接和短连接_Http长连接和短连接_UDP长连接和短连接
查看>>
Netty工作笔记0063---WebSocket长连接开发2
查看>>
Netty工作笔记0070---Protobuf使用案例Codec使用
查看>>
Netty工作笔记0072---Protobuf内容小结
查看>>
Netty工作笔记0077---handler链调用机制实例4
查看>>
Netty工作笔记0081---编解码器和处理器链梳理
查看>>
Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
查看>>
Netty工作笔记0085---TCP粘包拆包内容梳理
查看>>
Netty常用组件一
查看>>
Netty常见组件二
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty心跳检测
查看>>
Netty心跳检测机制
查看>>
Netty核心模块组件
查看>>
Netty框架内的宝藏:ByteBuf
查看>>