Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.atomic.*;
- public class ParkingLot{
- private int capacity;
- AtomicInteger cars;
- boolean isFull(){
- if(cars.get() == capacity){
- return true;
- }
- return false;
- }
- boolean isEmpty(){
- if(cars.get() == 0){
- return true;
- }
- return false;
- }
- ParkingLot(int capacity){
- this.capacity=capacity;
- cars= new AtomicInteger(0);
- //Producer
- new Thread(){
- public void run(){
- synchronized(cars){
- while(true){
- while(isFull()){
- try{
- cars.wait();
- }
- catch(InterruptedException ex){}
- }
- System.out.println("TOTAL CARS:"+cars.get()+"/"+capacity+" | Adding new car");
- cars.getAndIncrement();
- try{
- sleep(1000);
- cars.notify();
- }
- catch(InterruptedException ex){}
- }
- }
- }
- }.start();
- //Consumer
- new Thread(){
- public void run(){
- synchronized(cars){
- while(true){
- while(isEmpty()){
- try{
- cars.wait();
- }
- catch(InterruptedException ex){}
- }
- System.out.println("TOTAL CARS:"+cars.get()+"/"+capacity+" | Removing a car");
- cars.getAndDecrement();
- try{
- sleep(1000);
- cars.notify();
- }
- catch(InterruptedException ex){}
- }
- }
- }
- }.start();
- }
- public static void main(String args[]){
- ParkingLot p= new ParkingLot(10);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement