我需要船只同時(shí)裝卸貨物。有沒(méi)有辦法在java中做到這一點(diǎn)?我設(shè)法讓多艘船同時(shí)在港口工作,但他們先卸貨,然后再裝載新的板條箱。那是我的 Ship 類(lèi)變體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貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
您試圖在單個(gè)線程中完成的正是多個(gè)線程的目的。多線程使您能夠以多種活動(dòng)可以在同一程序中同時(shí)進(jìn)行的方式編寫(xiě):
多線程程序包含兩個(gè)或多個(gè)可以并發(fā)運(yùn)行的部分,每個(gè)部分可以同時(shí)處理不同的任務(wù),從而優(yōu)化利用可用資源,特別是當(dāng)您的計(jì)算機(jī)有多個(gè) CPU 時(shí)。
根據(jù)定義,多任務(wù)處理是指多個(gè)進(jìn)程共享公共處理資源(例如 CPU)。多線程將多任務(wù)的概念擴(kuò)展到應(yīng)用程序中,您可以在其中將單個(gè)應(yīng)用程序中的特定操作細(xì)分為單獨(dú)的線程。每個(gè)線程都可以并行運(yùn)行。操作系統(tǒng)不僅在不同的應(yīng)用程序之間劃分處理時(shí)間,而且在應(yīng)用程序內(nèi)的每個(gè)線程之間劃分處理時(shí)間。
在此處閱讀有關(guān) Java 多線程的更多信息。
添加回答
舉報(bào)
0/150
提交
取消