Java 使用Thread类,模拟龟兔赛跑

使用Thread类,模拟龟兔赛跑

package test1;
public  class test1 extends Thread 
{
    
    
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
    
    
		// TODO Auto-generated method stub
		Thread Rabbit = new Thread (new test1 ("rabbit",15,50));
		Thread Turtle = new Thread (new test1 ("turtle",12,50));
		Turtle.start();
		Rabbit.start();
		System.out.println("This is the main application.");
	}
	String name;
	int speed;
	int distance;
	int curdistance;
	
	public test1 (String name,int speed,int distance)
	{
    
    
		this.name = name;
		this.speed = speed;
		this.distance = distance;
	}
	
	public void run()
	{
    
    
		while(curdistance<distance)
		{
    
    
			try
			{
    
    
				Thread.sleep((long)(Math.random()*1000)+500);
			}catch(InterruptedException e)
			{
    
    
				e.printStackTrace();
			}
			curdistance += speed*Math.random();
			System.out.println(name+": I am at "+curdistance);
		}
		System.out.println(name+" end!");
	}
}

猜你喜欢

转载自blog.csdn.net/tenju/article/details/121524639