⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 race.java

📁 一个龟兔赛跑的多线程源码
💻 JAVA
字号:
import java.awt.*;
import java.lang.Math;
import java.lang.Thread;

public class Race
{
  public static void main (String args []) 
  {  Animat rabbit = new Animat("Rabbit", 5 , 50);
     Animat turtle = new Animat("Turtle", 3 , 50);
     Thread myThread1 = new Thread (rabbit);
     Thread myThread2 = new Thread (turtle);
     myThread1.start(); 
     myThread2.start(); 
     System.out.println("This is the main application.");
  }
}

class Animat implements Runnable
{
  private String name;
  private int speed;
  private int distance;
  private int curdistance = 0;

  public Animat (String name, int speed, int distance)
  {
    this.name = name;
    this.speed = speed;
    this.distance = distance;
  }
  
  public void run()
  {
    while ( curdistance < distance )
    {
      try
      { Thread.sleep ( (int) (Math.random() * 1000) + 500 );      
      }
      catch (Exception e) {} 
      curdistance += (int) (Math.random () * speed ) + 1;
      System.out.println (name + " : i am at " + curdistance );
    }
    System.out.println (name + " have finished ! ");
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -