1 package simulation;
2
3 import java.util.Random;
4
5 class Vehicle
implements Runnable{
6 private int id;
7 private static TollBooth toll =
new TollBooth();
8 public Vehicle(
int id ) {
9 this.id=
id;
10 }
11 public void run () {
12 //1开始旅程
13 System.out.println("Vericle "+(id+1)+"starts journey"
);
14 Random RandGen =
new Random();
15 int Rnd =RandGen .nextInt(100
);
16 //2到达收费站
17 travel(Rnd);
18 System.out.println("Vericle"+(id+1)+"arrives at the toll"
);
19 //3通过收费站useToll方法要么是同步方法,要么是方法中有同步语句块
20 toll.useToll(
this);
21 //4离开收费站
22 travel(Rnd);
23 //通过桥梁
24
25 System.out.println("Vericle"+(id+1)+"has cross the bridge"
);
26 }
27 public int getVericleId() {
28 return this.id;
29
30 }
31 public void travel (
int time) {
32 int limit =500000
;
33 for(
int j=0;j<time;j++
) {
34 for(
int k=0;k<limit;k++
) {
35 }
36 }
37 }
38 }
39 //收费站
40 class TollBooth {
41 boolean inUse;
42 public TollBooth() {
43 inUse =
false;
44 }
45 public void useToll(Vehicle vehicle) {
46 while(
true) {
47 if(inUse==
false) {
48 synchronized (
this) {
49 inUse=
true;
50 System.out.println("Vericle"+(vehicle.getVericleId()+1)+"enters toolboth "
);
51 vehicle.travel(50
);
52 System.out.println("Vehicle"+(vehicle.getVericleId()+1)+"exits toolbooth"
);
53 inUse =
false;
54 break;
55 }
56 }
57 }
58 }
59 }
60 public class Simulate {
61 private static int noOfVehicles=5
;
62 private static Vehicle[] vehicles;
63 public static void main(String args[]) {
64 try {
65 Simulate sm=
new Simulate();
66 vehicles=
new Vehicle[5
];
67 for(
int i=0;i<noOfVehicles;i++
) {
68 vehicles[i]=
new Vehicle(i);
69 Thread t=
new Thread(vehicles[i]);
70 t.start();
71 Thread.sleep(10
);
72 }
73 }
74 catch(Exception ex) {
75 System.out.println(ex);
76 }
77 }
78
79 }
View Code
测试结果:
转载于:https://www.cnblogs.com/Catherinezhilin/p/9081140.html
相关资源:JAVA上百实例源码以及开源项目