我需要船只同時裝卸貨物。有沒有辦法在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); }}和港口
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
您試圖在單個線程中完成的正是多個線程的目的。多線程使您能夠以多種活動可以在同一程序中同時進行的方式編寫:
多線程程序包含兩個或多個可以并發運行的部分,每個部分可以同時處理不同的任務,從而優化利用可用資源,特別是當您的計算機有多個 CPU 時。
根據定義,多任務處理是指多個進程共享公共處理資源(例如 CPU)。多線程將多任務的概念擴展到應用程序中,您可以在其中將單個應用程序中的特定操作細分為單獨的線程。每個線程都可以并行運行。操作系統不僅在不同的應用程序之間劃分處理時間,而且在應用程序內的每個線程之間劃分處理時間。
在此處閱讀有關 Java 多線程的更多信息。
添加回答
舉報
0/150
提交
取消