Java--多執行緒--類比車輛進入入收費

來源:互聯網
上載者:User

標籤: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--多執行緒--類比車輛進入入收費

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.