Untitled

 avatar
unknown
plain_text
3 years ago
1.9 kB
4
Indexable
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 + " is waiting for a permit.");
      
        sem.acquire();
      
        System.out.println(name + " gets a permit.");
  
        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 + " releases the permit.");
         sem.release();
		}
		else {
			
			try {
	        System.out.println(name + " is waiting for a permit.");
	      
	        sem.acquire();
	      
	        System.out.println(name + " gets a permit.");
	  
	        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 + " releases the permit.");
             sem.release();
		}//		System.out.println(this.getPriority() + this.getName());

		
	}

}

public class sync {
	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();
	
		
	}
}
Editor is loading...