Java多线程——龟兔赛跑

Java多线程——龟兔赛跑,第1张

Java多线程——龟兔赛跑

题目:龟兔进行50m赛跑,乌龟速度为1,兔子为5,决出胜利者

public class Competition implements Runnable {
	int length1=0;
	int length2=0;
	Thread tortoise,rabbit;
	Competition(){
		tortoise=new Thread(this);
		rabbit=new Thread(this);
		tortoise.setName("乌龟");
		rabbit.setName("兔子");
	}
	public static void main(String[]args) {
		Competition c=new Competition();
		c.tortoise.start();
		c.rabbit.start();
	}
	public void run() {
		if(Thread.currentThread().getName().equals("乌龟")) {
			System.out.println("乌龟起跑...");
			for(int i=1;i<=50;i++) {
				System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
				length1+=1;
				try {Thread.sleep(200);
				}
				catch(InterruptedException e) {}
				if(length2==50)
					break;
				else if(length1==50) {
					System.out.println(Thread.currentThread().getName()+"跑完了全程");
					System.out.println("胜利者是"+Thread.currentThread().getName());
				}
			}
		}
		else if(Thread.currentThread().getName().equals("兔子")) {
			System.out.println("兔子起跑...");
			for(int i=5;i<=50;i+=5) {
				System.out.println(Thread.currentThread().getName()+"跑了"+i+"米");
				length2+=5;
				try {Thread.sleep(1000);
				}
				catch(InterruptedException e) {}
				if(length1==50)
					break;
				else if(length2==50) {
					System.out.println(Thread.currentThread().getName()+"跑完了全程");
					System.out.println("胜利者是"+Thread.currentThread().getName());
				}
			}
		}
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5659332.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存