나는 스레드와 동기화 된 메서드의 사용을 구현하는 큰 숙제를 작업하고 있습니다. 이전에는 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();
}
}
뭔가 부족합니다. 누가 음식을 저장실에서 제거하나요? 언제 그것을 제거합니까? –
이 예에서는 쓰레기통을 숙제로 사용하지만 다른 유형의 작업자는 스레드로도 사용됩니다. – vedran