java利用多线程编写赛马程序

AKUK 2015-11-18 11:57:28
利用多线程编写赛马程序,赛程长1000米,红马速度为0-20米/秒之间的随机数,黑马速度为0-19米/秒之间的随机数,白马速度为0-18米/秒之间的随机数。每10秒马匹速度更新,并刷新显示每匹马完成的距离,直到所有马到达终点,给出名次及各自的完成时间。
...全文
923 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
三仙半 2015-11-19
  • 打赏
  • 举报
回复
这个练习应该是多线程之中最简单的,因为,没有共享数据,也没有进程相关。 马类:

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("比赛结束");
		}
	}
}
  • 打赏
  • 举报
回复
看到线程都想吐的路过,,,,,平时项目都尽量避开线程,,,难调试啊。。。。

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧