java多线程模拟停车系统

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

import sun.awt.geom.AreaOp.IntOp;

/**
*

  • @author Administrator
  • 多线程停车系统模型
    */
    public class test2 {
    // private static final SynchronousQueue sq = new SynchronousQueue();
    //新建5个停车位
    Random random = new Random();
private static final BlockingQueue carPakingSpace = new ArrayBlockingQueue(5);

// private void parkingSeat(String cars) {
// System.out.println(cars+“停车”);
// }
public static void main(String[] args) {
new test2().Cars();
}
// 车位系统
// privat5e void

//初始化车辆
private void Cars() {
    

    //现有20辆车子要来停车,但是每1秒只能停1辆车子
    final Semaphore _Semaphore = new Semaphore(1);
    for(int i=0 ; i<20; i++) {
        new Thread(new Runnable() {
            
            public void run() {

// while(true) {

                try {
                    _Semaphore.acquire();
                    pakingCars(Thread.currentThread().getName());
        
                    //每一秒只能停1辆车
                    Thread.sleep(1000);
                    _Semaphore.release();
                    
                    
                    
                    //模拟停车的时间
                    Thread.sleep(random.nextInt(4000)+1000);
                    //离开了
                    leaveCars(Thread.currentThread().getName());
                    
                    
                
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
                
            }
        }).start();
    }
}

//准备离开的车
private void leaveCars(String cars) {
    try {
        System.out.println(carPakingSpace.take()+"-----离开了");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
//停车
private void pakingCars(String cars) {
    try {
        carPakingSpace.put(cars);
        System.out.println(cars+": 停车");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

你可能感兴趣的:(java算法,java)