Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.concurrent.Semaphore;
  4.  
  5. public class Main {
  6.  
  7. static Semaphore semaphore = new Semaphore(4);
  8.  
  9. public static void main(String[] args) {
  10. System.out.println("Max 4 books");
  11. StudentThread t1 = new StudentThread("1 Student");
  12. StudentThread t2 = new StudentThread("2 Student");
  13. StudentThread t3 = new StudentThread("3 Student");
  14. StudentThread t4 = new StudentThread("4 Student");
  15. StudentThread t5 = new StudentThread("5 Student");
  16.  
  17. t1.start();
  18. t2.start();
  19. t3.start();
  20. t4.start();
  21. t5.start();
  22. }
  23.  
  24. static class StudentThread extends Thread {
  25. private String name = "";
  26.  
  27. public StudentThread(String name) {
  28. this.name = name;
  29. }
  30.  
  31. @Override
  32. public void run() {
  33. super.run();
  34. try {
  35. System.out.println(name + " : lock");
  36. System.out.println("Available books: " + semaphore.availablePermits());
  37.  
  38. semaphore.acquire();
  39. System.out.println(name + " got permit for book");
  40.  
  41. // method for get book from db
  42.  
  43. try {
  44. Thread.sleep(2000);
  45. } finally {
  46. System.out.println(name + " book returned");
  47.  
  48. // method for return book
  49.  
  50. semaphore.release();
  51. }
  52.  
  53. } catch (InterruptedException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement