Guest User

Untitled

a guest
Dec 15th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. package javacore.threading;
  2.  
  3. import java.util.concurrent.Semaphore;
  4.  
  5. public class SemaphoreExample {
  6. private static final int DEFAULT_PERMITS = 2;
  7. private static final int NO_OF_THREADS = 4;
  8. private Semaphore semaphore = new Semaphore(DEFAULT_PERMITS);
  9.  
  10.  
  11. private class SemaphoreTestThread implements Runnable {
  12. @Override
  13. public void run() {
  14. try {
  15. for(int i=0;i<NO_OF_THREADS;i++) {
  16. //Acquiring context here
  17. semaphore.acquire();
  18. System.out.println("Semaphore acquired: "+ Thread.currentThread().getName());
  19.  
  20. // only ever two threads here
  21. Thread.sleep(1000);
  22. //Releasing context here
  23. semaphore.release();
  24. System.out.println("Semaphore released: "+ Thread.currentThread().getName());
  25. }
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31.  
  32. private void init() {
  33. for(int i=0; i<NO_OF_THREADS; ++i) {
  34. Thread th = new Thread(new SemaphoreTestThread());
  35. th.start();
  36. }
  37. }
  38.  
  39. public static void main(String[] args) {
  40. new SemaphoreExample().init();
  41. }
  42. }
Add Comment
Please, Sign In to add comment