CodesJava

Easy learning with example program codes

semaphore in java


The java.util.concurrent.Semaphore class represents a counting semaphore. It is used to control the access of shared resource with the help of a counter. A semaphore is initialized with the given number which represents the number of permits. If counter is greater than 0 then for each call to the acquire() method, a permit is given to the calling thread and semaphore’s counter will be decremented by 1 otherwise the thread will be blocked until a permit can be acquired. When a thread not required the shared resource, it will release the permit and counter will be incremented by 1.

Note: counter represents the number of threads which can access the shared resources at a time.

Example

import java.util.concurrent.Semaphore;
 
class Shared {
    static int count = 0;
}
 
class TestThread extends Thread {
    Semaphore sem;
    String threadName;
    public TestThread(Semaphore sem, String threadName) {
        super(threadName);
        this.sem = sem;
        this.threadName = threadName;
    }
 
    @Override
    public void run() {         
        if(this.getName().equals("Test1")) {
            System.out.println("Starting " + threadName);
            try {
                System.out.println(threadName + " is waiting for a permit.");
                //Acquiring the lock
                sem.acquire();
                System.out.println(threadName + " gets a permit.");               
                for(int i=0; i < 3; i++) {
                    Shared.count++;
                    System.out.println(threadName + ": " + Shared.count);
                    Thread.sleep(10);
                }
            } catch (InterruptedException exc) {
                    System.out.println(exc);
            }
 
            //Release the permit.
            System.out.println(threadName + " releases the permit.");
            sem.release();
        } else {
            System.out.println("Starting " + threadName);
            try {
                System.out.println(threadName + " is waiting for a permit.");
                // acquiring the lock
                sem.acquire();
                System.out.println(threadName + " gets a permit.");
                for(int i=0; i < 3; i++)
                {
                    Shared.count--;
                    System.out.println(threadName + ": " + Shared.count);
                    Thread.sleep(10);
                }
            } catch (InterruptedException exc) {
                System.out.println(exc);
            }
            // Release the permit.
            System.out.println(threadName + " releases the permit.");
            sem.release();
        }
    }
}
 
public class SemaphoreTest {
    public static void main(String args[]) throws InterruptedException {
        Semaphore sem = new Semaphore(1);
        TestThread testThread1 = new TestThread(sem, "Test1");
        TestThread testThread2 = new TestThread(sem, "Test2");
 
        testThread1.start();
        testThread2.start();
 
        testThread1.join();
        testThread2.join();
 
        System.out.println("count: " + Shared.count);
    }
}

Output

Starting Test1
Starting Test2
Test1 is waiting for a permit.
Test2 is waiting for a permit.
Test1 gets a permit.
Test1: 1
Test1: 2
Test1: 3
Test1 releases the permit.
Test2 gets a permit.
Test2: 2
Test2: 1
Test2: 0
Test2 releases the permit.
count: 0

Related topics

Posted in Java   

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap