案例:龟兔赛跑
package com.chengguo.线程; /** * 模拟:龟兔赛跑 */ public class Demo_20200509003_ThreadRace implements Runnable { private static String winner; @Override public void run() { for (int i = 0; i <= 100; i++) { //模拟兔子休息 if (Thread.currentThread().getName().equals("兔子")&&(i+1)%10==0){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } //判断比赛是否结束 boolean flag = gameOVer(i); //如果比赛结束,程序停止 if (flag) { break; } System.out.println(Thread.currentThread().getName() + "跑了" + i + "步"); } } //判断是否完成比赛 private boolean gameOVer(int step) { //已经存在胜利者 if (winner != null) { return true; } else { if (step >= 100) { //获取胜利者名字(线程名字) winner = Thread.currentThread().getName(); System.out.println("winner is " + winner); return true; } } return false; } public static void main(String[] args) { //创建runnable接口的实现类对象 Demo_20200509003_ThreadRace dt = new Demo_20200509003_ThreadRace(); //创建一个线程对象,通过线程对象来开启线程 new Thread(dt, "兔子").start(); new Thread(dt, "乌龟").start(); } }