java 用多线程模拟龟兔赛跑: 5
乌龟和兔子进行1000米赛跑,兔子前进5米,乌龟只能前进1米。但兔子每20米要休息500毫秒,而乌龟是每100米休息500毫秒。谁先到终点就结束程序,并显示获胜方...
乌龟和兔子进行1000米赛跑,兔子前进5米,乌龟只能前进1米。但兔子每20米要休息500毫秒,而乌龟是每100米休息500毫秒。谁先到终点就结束程序,并显示获胜方
展开
1个回答
展开全部
public class TortoiseAndHareRace {
public static void main(String[] args) {
Runnable vs=new Race();
Thread hare=new Thread(vs,"Hare");
Thread tortoise =new Thread(vs,"Tortoise");
System.out.println("Ready!GO!");
hare.start();
tortoise.start();
}
}
class Race implements Runnable{
private static final int S=1000;
@Override
public void run() {
if(Thread.currentThread().getName().equals("Hare")){
int sHare=0;
while(sHare<=S){
sHare+=5;
if(sHare%20==0)
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
}
}else{
int sTortoise=0;
while(sTortoise<=S){
sTortoise++;
if(sTortoise%100==0)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Runnable vs=new Race();
Thread hare=new Thread(vs,"Hare");
Thread tortoise =new Thread(vs,"Tortoise");
System.out.println("Ready!GO!");
hare.start();
tortoise.start();
}
}
class Race implements Runnable{
private static final int S=1000;
@Override
public void run() {
if(Thread.currentThread().getName().equals("Hare")){
int sHare=0;
while(sHare<=S){
sHare+=5;
if(sHare%20==0)
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
}
}else{
int sTortoise=0;
while(sTortoise<=S){
sTortoise++;
if(sTortoise%100==0)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询