/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	    public static void main(String[] args) throws InterruptedException {
        Car[] cars = new Car[]{
                new Car("Honda"),
                new Car("AMG"),
                new Car("Ford"),
                new Car("Nissan")
        };

        final Spot[] spots = new Spot[]{
          new Spot(1),
          new Spot(2),
          new Spot(3)
        };

        List<Thread> threads = new ArrayList<>();

        for (final Car c : cars){
            final Runnable r = new Runnable() {
                @Override
                public void run() {
                    try {
                        c.go(spots);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };

            final Thread t = new Thread(r);
            threads.add(t);
            t.start();
        }

        Thread.sleep(TimeUnit.SECONDS.toMillis(5));

        for(Thread t : threads){
            t.interrupt();
        }
    }

    public static class Spot {
        public final AtomicBoolean occupied = new AtomicBoolean(false);
        public final int id;

        public Spot(int id) {
            this.id = id;
        }
    }

    public static class Car {
        private final String name;

        public Car(String name) {
            this.name = name;
        }

        public void go(Spot[] spots) throws InterruptedException {
            int i = 0;
            while (!Thread.interrupted()){
                Spot s = spots[i];
                if(s.occupied.compareAndSet(false,true)){
                    use(s);
                }else {
                    i++;
                    i = i >= spots.length ? 0 : i;
                }
            }
        }

        private void use(Spot spot) throws InterruptedException {
            System.out.println(String.format("Car %s parked @ spot %d.",name,spot.id));
            Thread.sleep((long) (Math.random()*1000));
            spot.occupied.set(false);
            System.out.println(String.format("Car %s left @ spot %d.",name,spot.id));
        }
    }
}