Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.1 kB
1
Indexable
Never
// 22 JULY 2022 roji LP 1 cha lab madhe keleli B1 Assignment Synchronization................


package lab31273;


import java.util.concurrent.*;

class Mobile {
	static int units = 0;
}

class Mythread extends Thread {

	Semaphore sem;
	String name;

	public Mythread(Semaphore sem, String name) {

		super(name);
		this.sem = sem;
		this.name = name;
	}

	@Override
	public void run() {
		
//		System.out.println(this.getPriority() + this.getName());
		
		if(this.getName().equals("Samsung")) {
		
//		System.out.println(name + " does not have access");
		
		try {
        System.out.println(name + " has consumers waiting for the product");
      
        sem.acquire();
      
        System.out.println(name + " starts production");
  
        for(int i=0; i < 5; i++)
        	{
            Mobile.units++;
            System.out.println(name + ": " + Mobile.units);
  
           
//            Thread.sleep(10);
        	}
        }catch(Exception e) {
        	System.out.println(e);
        	}
		
		 System.out.println(name + " stops the production according to the requirement");
         sem.release();
		}
		else {
			
			try {
//	        System.out.println(name + " is waiting for a permit.");
	      
	        sem.acquire();
	      
	        System.out.println(name + " Consumer start buying samsung products");
	        
	        if(Mobile.units != 0) {
	        	for(int i=0; i < 5; i++)
	        	{
	            Mobile.units--;
	            System.out.println(name + ": " + Mobile.units);
	  
	            
//	            Thread.sleep(10);
	        	}
	        }	        
	        
	        }catch(Exception e) {
	        	System.out.println(e);
	        }
			
//			 System.out.println(name + " ");
             sem.release();
		}//		System.out.println(this.getPriority() + this.getName());

		
	}

}

public class lab31273 {
	public static void main(String args[]) throws InterruptedException {

		Semaphore sem = new Semaphore(1);

		Mythread Mt1 = new Mythread(sem, "Samsung");
		Mythread Mt2 = new Mythread(sem , "Tanmay");
		
		
		Mt1.start();
		
		Mt1.join();
		
		Mt2.start();

//		Mt2.join();
	
		
	}
}