Advertisement
Guest User

vmp123

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