標籤:imu 同步 print false open set art ati view
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
測試結果:
Java--多執行緒--類比車輛進入入收費