多线程基本练习

龟兔赛跑,龟兔在进行赛跑,兔子每步跑5米,乌龟每步跑1米,兔子每跑1步,休息1秒钟,乌龟每跑1步,休息0.2秒。乌龟或兔子谁先跑到50米,谁就胜出

代码如下

package maincode;

class Rabbit implements Runnable{
	private int path=0;
	private int length=0;
	@Override
	public void run() {
		while(true) {
		if(length<50) {
			path++;
			length=path*5;
			System.out.println("兔子 步数:"+path+"  长度:"+length);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			System.out.println("兔子获胜");
			System.exit(0);
		}
		}
		}
	}
class Tor implements Runnable{
	private int path=0;
	private int length=0;
	@Override
	public void run() {
		while(true) {
		if(length<50) {
			path++;
			length=path;
			System.out.println("乌龟 步数:"+path+"  长度:"+length);
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			System.out.println("乌龟获胜");
			System.exit(0);
		}
		}
		}
	}
public class One {
  public static void main(String[] args) {	  	
	  new Thread(new Rabbit()).start();
	  new Thread(new Tor()).start();  
}
}

多线程基本练习_第1张图片
代码仅供参考!

你可能感兴趣的:(多线程基本练习)