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