多线程实战-龟兔赛跑

多线程实战,

 

 

这个图解释的很形象,开启多线程之后,子线程与主线程并行运行。

package com.xin.myThread01;
public class Race implements Runnable{ //胜利者,winner一定要用全局变量,如果用局部变量,就会出现两个胜利者,因为两个线程,互不干扰 private static String winner; @Override public void run() { for (int i = 0; i <=100; i++) { if(Thread.currentThread().getName().equals("兔子")&&i%10==0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } boolean flag = gameOver(i); if (flag){ break; } System.out.println(Thread.currentThread().getName()+"--->跑了"+i+"步"); } } // 判断是否结束比赛 private boolean gameOver(int steps){ if(winner!=null){ return true; }else { 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(); } }

 

思路来源:B站狂神说多线程

 

posted @ 2021-03-22 10:03  进阶的蜗牛  阅读(38)  评论(0编辑  收藏  举报