赛道相当于一个资源,乌龟和兔子相当于两个线程,多线程共用一个资源
package com.demo01; public class Race implements Runnable{ private static String winner; @Override public void run(){ for(int i=0;i<=100;i++){ if(Thread.currentThread().getName()=="兔子" && i%20==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; }{ if(steps>=100){ winner=Thread.currentThread().getName(); System.out.println("winner is"+Thread.currentThread().getName()); } } return false; } public static void main(String[] args){ Race race=new Race(); new Thread(race,"兔子").start(); new Thread(race,"乌龟").start(); } }
标签:赛跑,龟兔,Thread,代码,winner,Race,race,new,public From: https://www.cnblogs.com/zhang12345/p/17143627.html