Using Semaphore to control access for resource - Java Thread

Java examples for Thread:Semaphore

Description

Using Semaphore to control access for resource

Demo Code



import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;



class SemWorker implements Runnable {
    private int index;
    private Semaphore semaphore;

    public SemWorker(int index, Semaphore semaphore) {
        this.index = index;
        this.semaphore = semaphore;
    }/*from  www .j  a  v  a 2s .  co m*/
    @Override
    public void run() {
        try{
            if(semaphore.availablePermits()>0){
                System.out.println("customer "+this.index+"enter with permit");
            }
            else{
                System.out.println("customer "+this.index+" enter without permit and wait");
            }
            semaphore.acquire();
            System.out.println("customer "+this.index+" got permit");
            Thread.sleep((int)(Math.random()*1000));
            System.out.println("customer "+this.index+" done using");
            semaphore.release();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

public class TestSemaphore {
    private static final int TASKCOUNT = 10;

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < TASKCOUNT; i++) {
            service.execute(new SemWorker(i, semaphore));
        }

        service.shutdown();
    }
}

Related Tutorials