我正在做一個大型的家庭作業,它實現了使用線程和同步方法。我以前從來沒有使用線程,所以這有點令人困惑。由於作業太大,我決定首先嚐試一個簡單的例子。所以,在這個例子中,我有4個類:Java,使用線程
Food
,一個只存儲的對象。Worker
誰「收集」食物並將其存儲在存儲器中。他的工作時間有限,每次他「收集」食物時都會減少。Storage
它作爲食物的容器和容量有限。Trash
- 沒有太大的對象,它只是用來從存儲
因此,通過定義刪除項目,Worker
必須是一個線程。他的run()
方法包含一個循環,該循環將使工作人員收集食物(創建食物的新實例)並將其存儲在一個堆棧中(Storage
)。每次成功的聚會都會縮短工作時間這個循環將重複,直到工作時間等於0.現在,這是我不明白如何讓線程等待。例如,一名工人有15個小時,存儲容量爲10個。因此,工作人員應該在存儲中增加10個新食品,增加其容量,並等待一些(外部)事件來增加容量或從存儲中移除食品所以他可以繼續「收集」食物並將其添加到存儲中。這裏是我當前的代碼:
import java.util.*;
class testSync {
public static void main(String[] args) {
/** Create a storage **/
Storage storage = new Storage();
/** Assign a worker to this storage **/
Worker worker = new Worker(storage);
/** Create a trash can **/
Trash trash = new Trash(storage);
/** Start new thread **/
new Thread(worker).start();
/** The thread should work until the maximum capacity of the storage has been reached **/
/** Throw item so that further items can be added **/
trash.throwItem();
}
}
/** WORKER CLASS **/
class Worker implements Runnable {
int work = 15;
Storage storage;
public Worker(Storage s) {
storage = s;
}
/** Run this method until working hours equal to zero **/
public void run() {
while (work > 0) {
System.out.println(work);
storage.store(new Food());
work--;
/** In case the capacity has been maxed out, wait for some event which will remove food items from the storage **/
if (!storage.hasSpace()) {
// WAIT FOR THE STORAGE TO BE EMPTIED AND THEN CONTINUE ADDING
}
}
}
}
/** TRASH CLASS **/
class Trash {
Storage storage;
public Trash(Storage s) {
storage = s;
}
/** Remove one item from the storage **/
public void throwItem() {
storage.load();
}
}
/** FOOD CLASS **/
class Food {
public Food() {}
}
/** STORAGE CLASS **/
class Storage {
private int cap = 10;
private Stack<Food> container = new Stack<Food>();
public Storage() {}
/** Check to see if there's any free space **/
public boolean hasSpace() {
if (container.size() < cap)
return true;
else
return false;
}
/** If capacity allows, add one an item to the storage **/
public void store(Food food) {
if (hasSpace()) {
container.push(food);
}
}
/** Remove one item from the fridge **/
public Food load() {
return container.pop();
}
}
東西丟失:誰從存儲中移除食物?它什麼時候刪除它? – 2011-12-17 17:36:48
在這個例子中垃圾桶,但在我的家庭作業中,另一種類型的工人也被用作線程。 – vedran 2011-12-17 18:25:42