Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.*;
- public class ParkingLot{
- private Map<Pair<Integer>,Date> park;
- private LinkedList<Pair<Integer>> occupPark;
- private int i;
- private int j;
- private int m;
- private int n;
- private int maxCars;
- public ParkingLot (int n,int m){
- this.n=n;
- this.m=m;
- maxCars=n*m;
- park = new HashMap<>();
- occupPark = new LinkedList<>();
- }
- public synchronized Pair<Integer> carIn(){
- Pair<Integer> pos;
- //Parcheggio Pieno
- if(maxCars<=0) return null;
- // Ci sono posti liberi "non continui"
- if (occupPark.size()>0){
- pos = occupPark.removeFirst();
- park.put(pos,new Date());
- maxCars--;
- return pos;
- }
- pos = new Pair<Integer> (i,j);
- park.put(pos,new Date());
- maxCars--;
- if(j==m && i!=n){
- j=0;
- i++;
- }
- else j++;
- return pos;
- }
- public int getMax(){return maxCars;}
- public synchronized Integer carOut(Pair pos){
- Date currDate = new Date();
- Set<Pair<Integer>> set = park.keySet();
- if(!set.contains(pos)) return null;
- Date carDate = park.get(pos);
- set.remove(pos);
- occupPark.add(pos);
- maxCars++;
- return currDate.getSeconds() - carDate.getSeconds();
- }
- public static void main(String[] args){
- final ParkingLot p =new ParkingLot(10,10);
- BlockingQueue<Pair<Integer>> cars = new LinkedBlockingQueue<>();
- Thread abusivo = new Thread(){
- @Override
- public void run(){
- Pair<Integer> pos;
- synchronized(cars){
- // Ci sono ancora posti auto
- while(p.getMax()>0){
- try{
- cars.wait(1000);
- cars.add(p.carIn());
- cars.notifyAll();
- }catch(InterruptedException e){}
- }
- cars.notifyAll();
- }
- }
- };
- Thread finanza = new Thread(){
- @Override
- public void run(){
- synchronized(cars){
- while(cars.size()>0 ){
- try{
- cars.wait(1000);
- System.out.println(p.carOut(cars.take()));
- cars.notifyAll();
- }
- catch(InterruptedException e){}
- }
- }
- cars.notifyAll();
- }
- };
- try{
- abusivo.start();
- finanza.start();
- abusivo.join();
- finanza.join();
- }
- catch(InterruptedException e){}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement