java实现龟兔赛跑
第一种方法
代码如下:
/** * */package a;/** * @author Administrator * */public class Race { public static void main(String arg[]) { Animal a1,a2; a1 = new Animal("rabit",100); a2 = new Animal("turtle",20); a2.setPriority(Thread.MAX_PRIORITY);//让乌龟的运行优先级更高 a1.start(); a2.start(); // TODO Auto-generated method stub }}class Animal extends Thread{ int speed;//速度 public Animal(String str,int speed){ super(str);//线程名用动物名代表 this.speed=speed; } public void run(){ int distance = 0; int sleepTime; while(distance<=1000){ System.out.println(getName()+"is at"+distance); try{ distance+=speed;//每次跑的距离简单用速度计算 sleepTime = (int)(speed+Math.random()*speed); //速度快休息时间更长 sleep(sleepTime); }catch(InterruptedException e){} } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
第二种方法
代码如下:
package b;import java.awt.*;import java.applet.*;import java.awt.event.*;public class tt extends Applet implements Runnable { int BeginX=200,EndX=400; int RabbitX=BeginX,RabbitY=100; int TortoiseX=BeginX,TortoiseY=200; int RabbitRestTime=800,TortoiseRestTime=50; int RabbitSpeed=15,TortoiseSpeed=1; int state=0; Thread rabbit; Thread tortoise; public void init(){ rabbit=new Thread(this,"rabbit"); tortoise=new Thread(this,"tortoise"); } public void paint(Graphics g){ setSize(600,350); g.drawString("龟",TortoiseX,TortoiseY); g.drawString("兔",RabbitX,RabbitY); g.setColor(Color.red); for(int j=70;j<=230;j+=10) g.drawString("|",EndX+8,j); g.setColor(Color.black); if(state==1) g.drawString("兔子赢了!!", 250, 300); else if(state==2) g.drawString("乌龟赢了!!", 250, 300); } public void start(){ rabbit.start(); tortoise.start(); } public void run(){ String currentRunning; while(state==0){ currentRunning=Thread.currentThread().getName(); if(currentRunning.equals("rabbit")){ try{ Thread.sleep((int)(Math.random()*RabbitRestTime)); } catch(InterruptedException e){} RabbitX+=RabbitSpeed; if(RabbitX>EndX)RabbitX=EndX; } else if(currentRunning.equals("tortoise")){ try{ Thread.sleep((int)(Math.random()*TortoiseRestTime)); } catch(InterruptedException e){} TortoiseX+=TortoiseSpeed; if(TortoiseX>EndX)TortoiseX=EndX; } if(RabbitX==EndX)state=1; else if(TortoiseX==EndX)state=2; repaint(); } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
网友评论