我有以下任务:
“港口。船舶进入港口以卸载/装载集装箱。港口和船舶上当前的集装箱数量必须为非负数,并且超过船舶的指定容量和港口容量。有多个泊位在港口中。一个泊位可以停泊船舶。该船可以在泊位装载,卸载或同时执行这两项操作。”
您不能使用synced关键字。
我组织了船队。当前船上的集装箱数量不可能超过船的承载能力。但是我不知道该怎么做:当前端口中的容器数量,该数量必须为非负数并且大于指定的端口容量。我也想不通如何在码头上装船,卸货或同时执行这两种操作?
Ship.java
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
public class Ship extends Thread {
private static final boolean[] PARKING_PLACES = new boolean[5];
private static final Semaphore SEMAPHORE = new Semaphore(5, true);
private int idShip;
private int currentNumOfContains;
private int maxNumOfContains;
private ReentrantLock locker;
Ship(int idShip, int currentNumOfContains, int maxNumOfContains, ReentrantLock locker) {
this.idShip = idShip;
this.currentNumOfContains = currentNumOfContains;
this.maxNumOfContains = maxNumOfContains;
this.locker = locker;
}
@Override
public void run() {
if (currentNumOfContains <= maxNumOfContains) {
System.out.printf("Ship №%d sailed to the pier.\n", idShip);
try {
SEMAPHORE.acquire();
int parkingNumber = -1;
locker.lock();
try {
for (int i = 0; i < 5; i++)
if (!PARKING_PLACES[i]) {
PARKING_PLACES[i] = true;
parkingNumber = i;
System.out.printf("Ship №%d moored at berth %d.\n", idShip, i);
break;
}
} finally {
locker.unlock();
}
Thread.sleep(5000);
locker.lock();
try {
PARKING_PLACES[parkingNumber] = false;
} finally {
locker.unlock();
}
SEMAPHORE.release();
System.out.printf("Ship №%d left the pier.\n", idShip);
} catch (InterruptedException ignored) { }
} else System.out.printf("Ship №%d drowned due to overload.\n", idShip);
}
}
Port.java
public class Port {
private int countOfDock;
private int maxNumOfContainers;
private int currentNumOfContainers;
public Port(int countOfDock, int maxNumOfContainers, int currentNumOfContainers, boolean freePlace) {
this.countOfDock = countOfDock;
this.maxNumOfContainers = maxNumOfContainers;
this.currentNumOfContainers = currentNumOfContainers;
}
}
Main.java
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
ReentrantLock locker = new ReentrantLock();
new Ship(1, 90, 100, locker).start();
Thread.sleep(400);
new Ship(2, 190, 100, locker).start();
Thread.sleep(400);
new Ship(3, 1, 100, locker).start();
Thread.sleep(400);
new Ship(4, 48, 100, locker).start();
Thread.sleep(400);
new Ship(5, 200, 100, locker).start();
Thread.sleep(400);
}
}
有人可以帮忙吗?我只是死胡同)