[英]Queue Simulation
您好,我嘗試使用Java模擬等待隊列。 我的程序必須包含以下內容:
好吧,我有一個空隊列對象,一個隨機字符串列表生成器,它將字符串發送到隊列。
但是,我所遇到的問題是隨機字符串生成器在循環中選擇重復項,我該如何解決? 另外,我如何使它以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]);
}
}
聽起來像是一個熟悉的問題: 生產者消費者問題
您應該熟悉System.currentTimeMillis()和Thread.sleep() 。 您應該考慮一個在工作(消費/生產)的循環,然后睡眠500毫秒,然后再次繼續循環。
到目前為止,Oki通過使用另一個類中的方法,使Ive設法使循環工作,以輸出客戶名稱和服務時間。 但是,如果用戶輸入第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);
}
}
隨機函數根據執行的時間生成一個數字。 因為for循環非常快,所以隨機函數會生成相同的數字。 嘗試使用循環中的代碼創建一個新函數,然后從循環中調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.