עבור לתוכן

עזרה עם תזמון משימות ב- java

Featured Replies

פורסם

יש לי את המחלקה הבא:

public class ForagersTask extends Task {
private ConcurrentLinkedQueue<Forager> foragers;
private long waitTime;

public ForagersTask(Collection<Forager> foragers, long refreshRate) {
// Saves the Foragers
this.foragers = new ConcurrentLinkedQueue<Forager>(foragers);
// Saves the wait time
waitTime = 1000 / refreshRate;
}

@Override
public void run() {
// Gets the first Forager
Forager current = foragers.poll();
// Checks if the Task should stop
while ((!terminate) && (current != null)) {
try {
// Performs the Forager action
current.act();
// Adds the Forager to the Queue
foragers.add(current);
} catch (NoMoreActionsException e) {
// The Forager is not added to the Queue
}
// Allows pause
allowPause();
try {
// Waits the required time
Thread.sleep(waitTime);
} catch (InterruptedException e) {
}
// Gets the next Forager
current = foragers.poll();
}
if (!terminate) {
// The current Task has ended
Simulation.getInstance().taskEnded();
}
}
}

מה שאני מנסה לעשות פה זה להפעיל משימה כלשהי ב- Thread נפרד כל כמה זמן (המחלקה Task יורשת מ- Runnable).

הפיתרון שלי במתודה run כרגע הוא עם sleep שזה מאוד מגעיל.

אז חשבתי להשתמש ב- Timer או משהו כזה ולפרק את הלולאה כך שכל איטרציה תתוזמן לפי הזמן שקיבלתי בבנאי.

אם שמתם לב, אחד מתנאי העצירה של הלולאה הוא כאשר התור ריק (current != null.)

התור מתרוקן מתישהו כי המתודה act שאני מפעיל זורקת מתישהו שגיאה.

השאלה שלי היא איך אני מבצע את התזמון ומפסיק אותו ברגע שהתור ריק בלי לבצע busy waiting (כלומר אני רק אפעיל את ה- Timer ואחר כך יקראו נגיד למתודה שעוצרת את ה- Thread)?

אשמח אם תענו מהר כי יש לי עוד דברים אחרים שתלויים בזה ואני צריך להגיש את התוכנית בקרוב.

פורסם

נשמע כאילו אתה מחפש את CountDownLatch.

ארכיון

דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.

דיונים חדשים