我需要船只同时装卸货物。有没有办法在java中做到这一点?
我设法让多艘船同时在港口工作,但他们先卸货,然后再装载新的板条箱。
那是我的 Ship 类变体
public class Ship implements Runnable {
String name;
Port port;
Queue<Goods> storage;
Pier pier;
int capacity;
int numOnBoard;
public Ship(String name, Port port, int capacity) {
this.name = name;
this.port = port;
storage = new LinkedBlockingDeque<>(capacity);
this.capacity = capacity;
int num=(int)(Math.random()*capacity);
numOnBoard=num;
for (int i = 0; i < num; i++) {
storage.add(new Goods());
}
}
public void run() {
try {
int unl = 0;
int l = 0;
pier = port.getPier();
System.out.println("Ship " + name + " taken " + pier.name);
while (unload()) {
if(unl>=numOnBoard) break;
unl++;
System.out.println("Ship " + name + " unloaded cargo.");
Thread.sleep(new Random(100).nextInt(500));
}
System.out.println("Ship " + name + " unloaded " + unl + " crates.");
Thread.sleep(100);
while (load()) {
l++;
System.out.println("Ship " + name + " loaded cargo.");
Thread.sleep(new Random(100).nextInt(500));
}
System.out.println("Ship " + name + " loaded " + l + " crates.");
port.releasePier(pier);
System.out.println("Ship " + name + " released " + pier.name);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private boolean unload() {
if (storage.size() <= 0) return false;
return port.addGoods(storage.poll());
}
private boolean load() {
if (storage.size() >= capacity) return false;
return port.takeGoods(storage,numOnBoard);
}
}
和港口
慕勒3428872
慕桂英3389331
随时随地看视频慕课网APP
相关分类