0
所以,嘿大家好,我實際上是編碼方面的新人,甚至在基本問題上也遇到很多問題。Java多線程:飛機和跑道案例研究示例
所以我的講師給這個案例研究:模擬一次可以容納1架飛機着陸的飛機數量和4條跑道。如果所有4條跑道都被佔用,其他飛機必須等待其中一架或更多飛機起飛。對我來說很難,所以我先嚐試2跑道和4架飛機。
平面是線程類,跑道是普通類。我到目前爲止已經完成:
主類
public class Main { public static void main(String[] args) { Runway r[] = new Runway[2]; for (int i = 0; i < r.length; i++) { r[i] = new Runway(i); } Plane p[] = new Plane[4]; for (int i = 0; i < p.length; i++){ p[i] = new Plane(i, r[0], r[1]); p[i].start(); } } }
跑道類
public class Runway { private int id; private Lock l; public boolean available = true; public Runway(int id){ this.id = id; l = new ReentrantLock(); } public boolean landing(int idp){ boolean i; i = l.tryLock(); if (i == true) { available = false; System.out.println("Plane " + idp + " is landing on Runway: " + id); } return i; } public void takeOff(int idp){ System.out.println("Plane " + idp + " is take off from Runway: " + id); available = true; l.unlock(); } }
平面類
public class Plane extends Thread { private Runway r1, r2; private int id, tag; private boolean i = false; public Plane(int id, Runway r1, Runway r2){ this.id = id; this.r1 = r1; this.r2 = r2; } public void run(){ if (i == false) { if (r1.available == true) { i = r1.landing(id); tag = 1; } else if (r2.available == true) { i = r2.landing(id); tag = 2; } } sleep(); if (tag == 1 & i == true){ r1.takeOff(id); i = false; } else if (tag == 2 & i == true) { r2.takeOff(id); i = false; } } private void sleep(){ try { Thread.sleep(new Random().nextInt(8)*100); }catch (Exception e){} } }
這是結果...
Plane 1 is landing on Runway: 0
Plane 3 is landing on Runway: 1
Plane 1 is take off from Runway: 0
Plane 3 is take off from Runway: 1
Process finished with exit code 0
並非所有飛機的落下,我知道這是基本的,但任何幫助表示讚賞:d
是否允許使用「同步」語句? – gapvision
是的,我可以使用任何方法bro @gapvision –
你的代碼只包含一次嘗試,所以它只會做一次嘗試,如果嘗試失敗,什麼也不做。所以最小的做法是添加一個*循環*直到嘗試成功。 – Holger