1 Packagesimulation;2 3 ImportJava.util.Random;4 5 classVehicleImplementsrunnable{6 Private intID;7 Private StaticTollbooth toll =Newtollbooth ();8 PublicVehicle (intID) {9 This. id=ID;Ten } One Public voidrun () { A //1 start of Journey -System.out.println ("vericle" + (id+1) + "starts Journey"); -Random Randgen =NewRandom (); the intRnd =randgen. Nextint (100); - //2 Arrival Toll Station - Travel (Rnd); -System.out.println ("vericle" + (id+1) + "arrives at the toll"); + //3 via Toll Station The Usetoll method is either a synchronous method or a synchronous statement block in the method -Toll.usetoll ( This); + //4 departure Toll station A Travel (Rnd); at //through the bridge - -System.out.println ("vericle" + (id+1) + "have cross the bridge"); - } - Public intGetvericleid () { - return This. ID; in - } to Public voidTravel (intTime ) { + intLimit =500000; - for(intj=0;j<time;j++) { the for(intk=0;k<limit;k++) { * } $ }Panax Notoginseng } - } the //Toll Station + classTollbooth { A BooleanInUse; the Publictollbooth () { +InUse =false; - } $ Public voidUsetoll (Vehicle Vehicle) { $ while(true) { - if(inuse==false) { - synchronized( This) { theInuse=true; -System.out.println ("vericle" + (Vehicle.getvericleid () +1) + "enters Toolboth");WuyiVehicle.travel (50); theSystem.out.println ("Vehicle" + (Vehicle.getvericleid () +1) + "Exits Toolbooth"); -InUse =false; Wu Break; - } About } $ } - } - } - Public classSimulate { A Private Static intNoofvehicles=5; + Private Staticvehicle[] vehicles; the Public Static voidMain (String args[]) { - Try { $Simulate sm=Newsimulate (); thevehicles=NewVehicle[5]; the for(inti=0;i<noofvehicles;i++) { thevehicles[i]=NewVehicle (i); theThread t=NewThread (Vehicles[i]); - T.start (); inThread.Sleep (10); the } the } About Catch(Exception ex) { the System.out.println (ex); the } the } + -}
View Code
Test results:
java--Multithreading--simulating vehicle entry charges