嗨,我试图用Java来模拟等待队列。我的程序必须包括:
Oki所以我拥有的是一个空队列对象,一个随机字符串列表生成器,它将字符串发送到队列中。
但是,我遇到的问题是随机字符串生成器在循环中选择重复,我如何解决这个问题?另外,我如何使它以0.5秒的间隔将客户发送到队列,我需要记录他们进入队列和离开队列的时间,这样我就可以输出在队列中花费的时间。我被困住了,不知道现在该怎么办?
public static Queue<String> line = new LinkedList<String> ();
public static void main(String[] args)
{
String[] list = {"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", };
int customer = list.length;
for (int x = 0; x < customer; x++ )
{
int cus = (int) (Math.random() * customer);
line.add(list[cus]);
}
}发布于 2013-04-01 19:10:22
听起来像是一个熟悉的问题:生产者消费者问题
发布于 2013-04-01 19:13:11
您应该熟悉System.currentTimeMillis()和Thread.sleep()。您应该考虑一个工作的循环(消费/生产),然后睡眠500毫秒,然后继续循环。
发布于 2013-04-02 21:28:25
到目前为止,Oki通过在另一个类中使用方法来输出客户名称和它们的时间,我已经成功地获得了循环。然而,如果用户输入第n个出纳员数量,则Im仍然被困住,这基本上意味着整个循环将运行x(输入第n个出纳员)。
Random ran = new Random();
while (!line.isEmpty())
{
System.out.println(line + "\n");
System.out.println("The queue has " + line.size() + " customers left");
Customer cus = line.remove();
System.out.println(cus.name + " queued at " + cus.getTime() + " <=== SERVED" + "\n");
// you will have to sleep a random number of seconds here
int wait = ran.nextInt(2) + 1; // will generate 1 or 2
try
{
Thread.sleep(wait * 1000);
}
catch(Exception e)
{
System.out.println("Sleep error: " + e);
}
}https://stackoverflow.com/questions/15749859
复制相似问题