我正在做一个大型的家庭作业,它实现了使用线程和同步方法。我以前从来没有使用线程,所以这有点令人困惑。由于作业太大,我决定首先尝试一个简单的例子。所以,在这个例子中,我有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