我正在做一个大型的家庭作业,它实现了Threads和synchronized方法的使用。我以前从未使用Threads,所以有点令人困惑。由于作业太大,我决定首先尝试一个简单的例子。所以,在这个例子中我有4个类:
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();
}
}
答案 0 :(得分:3)
看一下BlockingQueue类 - 如果你正确实现它,你可以使用类似于worker可以调用的东西,但是在队列(Storage)有对象空间之前它不会返回。
答案 1 :(得分:3)
在存储上创建同步方法,在接受存储时返回true。像这样......
public synchronized boolean store ( int num) {
if ( items < capacity ) {
items ++;
return true;
}
return false;
}