Monday, September 18, 2017

lock an object by using Semaphores

AIM: the main aim this program is to use a Synchronized method to lock an object by using Semaphores 
import java.util.concurrent.Semaphore;
public class SemaphoreTest1 {

    Semaphore binary = new Semaphore(1);
 
    public static void main(String args[]) {
        final SemaphoreTest1 test = new SemaphoreTest1();
        new Thread(){
            @Override
            public void run(){
              test.mutualExclusion();
            }
        }.start();
     
        new Thread(){
            @Override
            public void run(){
              test.mutualExclusion();
            }
        }.start();
     
    }
 
    private void mutualExclusion() {
        try {
            binary.acquire();

            //mutual exclusive region
            System.out.println(Thread.currentThread().getName() + " inside mutual exclusive region");
            Thread.sleep(1000);

        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            binary.release();
            System.out.println(Thread.currentThread().getName() + " outside of mutual exclusive region");
        }
    }
 

}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home