62,635
社区成员




public class House implements Runnable
{
private Racing racing;
private int maxVelicity;
private String color;
private long orgin_time;
private long s_time;
private float position;
private long oldTime;
private int velicity;
/**
*
*/
public House(Racing racing, int maxVelicity, String color)
{
this.racing = racing;
this.maxVelicity = maxVelicity;
this.color = color;
orgin_time = System.currentTimeMillis();
s_time = orgin_time;
velicity = randomVelicity();
position = 0;
}
/**
* 随机产生马的速度
*
* @return
*/
private int randomVelicity()
{
return (int) Math.round((float) Math.random() * maxVelicity);
}
@Override
public void run()
{
System.out.println(color + "马改变速度:" + velicity);
oldTime = System.currentTimeMillis();
long curTime;
long deltaTime;
while (position < 1000)
{
curTime = System.currentTimeMillis();
deltaTime = curTime - oldTime;
// 每10秒重新随机马的速度
if (curTime - s_time > 10 * 1000)
{
velicity = randomVelicity();
System.out.println(color + "马改变速度:" + velicity + ", 当前位置:" + position);
// 重置计时起点
s_time = curTime;
}
float delta = velicity * 1.0f * deltaTime / 1000;
position += delta;
oldTime = curTime;
}
System.out.println(color + "马用时" + ((System.currentTimeMillis() - orgin_time) * 1.0 / 1000) + "秒");
racing.end(this);
}
public boolean equals(House house)
{
return house.getColor().equals(this.color);
}
public String getColor()
{
return color;
}
}
比赛类:
public class Racing
{
public static void main(String[] args)
{
Racing racing = new Racing();
racing.start();
}
private House red;
private House white;
private House black;
private boolean redEnd = false;
private boolean whiteEnd = false;
private boolean blackEnd = false;
public Racing()
{
red = new House(this, 50, "红");
black = new House(this, 49, "黑");
white = new House(this, 48, "白");
}
public void start()
{
new Thread(red).start();
new Thread(black).start();
new Thread(white).start();
}
public void end(House house)
{
if (house.equals(red))
{
redEnd = true;
}
else if (house.equals(white))
{
whiteEnd = true;
}
else if (house.equals(black))
{
blackEnd = true;
}
if (redEnd && whiteEnd && blackEnd)
{
System.out.println("--------------------------");
System.out.println("比赛结束");
}
}
}