luni, 23 noiembrie 2015

Java : Semaphore sample

package SemaphoreSample;

import java.util.concurrent.Semaphore;

public class StatViewsSample {
public static void main(String[] args) {
// assume that only two statistics providers are available
Semaphore statProviders = new Semaphore(2);
// list of views waiting to access the statistics providers
new StatView(statProviders, "User 1 View Chart");
new StatView(statProviders, "User 1 View 2 Grid");
new StatView(statProviders, "User 2 View Chart");
new StatView(statProviders, "User 3 View Chart");
new StatView(statProviders, "User 3 View 2 Chart");
new StatView(statProviders, "User 3 View 3 Grid");
}
}

class StatView extends Thread {
private Semaphore statProvider;

public StatView(Semaphore statProviders, String name) {
this.statProvider = statProviders;
this.setName(name);
this.start();
}

public void run() {
try {
System.out.println(getName()
+ " waiting to access an Statistics provider");
statProvider.acquire();
System.out.println(getName()
+ " is accessing an Statistics provider");
Thread.sleep(1000); // simulate the time required for using the
// Statistics provider
System.out.println(getName()
+ " is done using the Statistics provider");
statProvider.release();
} catch (InterruptedException ie) {
System.err.println(ie);
}
}
}