bonjours tout le monde
je vais vous expliquer le problem:
en fait je dois faire un programme en java qui utilise les thread, c'est une similation du traffic de voiture sur un pont qui laisse passer seulement une seule voiture dans un sens ou un autre, avec la possibiliter de parker trois voiture a droite et trois a gauche sur le pont dans le cas ou deux voiture se croise a mi-chemin, en fait j'ai reussi a faire ca mais avec un parking illimité(a droite et a gauche) ,et je dois le reduire a trois a gauche et trois a droite.
bridge
circulation
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 public class Bridge { protected String state; protected int nVehicles; public String name; public Bridge(String name){ state = new String("free"); nVehicles=0; this.name =name; } public synchronized void getBridge(String direction){ while(!(state.equals("free")|| state.equals(direction))){ try{ wait(); } catch(InterruptedException e){ System.err.println(e); } } state = direction; nVehicles++; } public synchronized void releaseBridge(){ nVehicles--; if(nVehicles==0){ state="free"; notifyAll(); } } }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 public class Circ { static Bridge left,right; public static void main(String arg[]){ left=new Bridge("leftBridge"); right= new Bridge("rightBridge"); for(int i=0; i<Math.random()*30;i++){ (new Vehicle("left vehicle "+i, "leftToRight")).start(); } for(int i=0; i<Math.random()*30;i++){ (new Vehicle("right vehicle "+i, "rightToLeft")).start(); } } }
vehicule
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 public class Vehicle extends Thread{ String name, direction; Bridge first,second; public Vehicle (String name, String direction){ this.name=name; this.direction = direction; if(direction.equals("leftToRight")){ first = Circ.left; second = Circ.right; } else{ second = Circ.left; first = Circ.right; } } public void run(){ int i; Bridge bridge; for(i=0,bridge=first;i<2;i++,bridge=second){ try { //to make random ask for the resources sleep((int)(Math.random()*200)); } catch (InterruptedException e){} bridge.getBridge(direction); System.out.println(name+ " Passing throw "+bridge.name +" in direction: " +direction); try { //to pass the bridge sleep(600); } catch (InterruptedException e){} bridge.releaseBridge(); } } }
Partager