Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javacore.threading;
- import java.util.concurrent.Semaphore;
- public class SemaphoreExample {
- private static final int DEFAULT_PERMITS = 2;
- private static final int NO_OF_THREADS = 4;
- private Semaphore semaphore = new Semaphore(DEFAULT_PERMITS);
- private class SemaphoreTestThread implements Runnable {
- @Override
- public void run() {
- try {
- for(int i=0;i<NO_OF_THREADS;i++) {
- //Acquiring context here
- semaphore.acquire();
- System.out.println("Semaphore acquired: "+ Thread.currentThread().getName());
- // only ever two threads here
- Thread.sleep(1000);
- //Releasing context here
- semaphore.release();
- System.out.println("Semaphore released: "+ Thread.currentThread().getName());
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- private void init() {
- for(int i=0; i<NO_OF_THREADS; ++i) {
- Thread th = new Thread(new SemaphoreTestThread());
- th.start();
- }
- }
- public static void main(String[] args) {
- new SemaphoreExample().init();
- }
- }
Add Comment
Please, Sign In to add comment