Advertisement
Guest User

vmpc12345

a guest
Jun 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 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.         books.add("book1");
  15.         books.add("book2");
  16.         books.add("book3");
  17.         books.add("book4");
  18.         StudentThread t1 = new StudentThread("1 Student");
  19.         StudentThread t2 = new StudentThread("2 Student");
  20.         StudentThread t3 = new StudentThread("3 Student");
  21.         StudentThread t4 = new StudentThread("4 Student");
  22.         StudentThread t5 = new StudentThread("5 Student");
  23.  
  24.         t1.start();
  25.         t2.start();
  26.         t3.start();
  27.         t4.start();
  28.         t5.start();
  29.     }
  30.  
  31.     static class StudentThread extends Thread {
  32.         private String name = "";
  33.  
  34.         public StudentThread(String name) {
  35.             this.name = name;
  36.         }
  37.  
  38.         @Override
  39.         public void run() {
  40.             super.run();
  41.             try {
  42.                 System.out.println(name + " : lock");
  43.                 System.out.println("Available books: " + semaphore.availablePermits());
  44.  
  45.                 semaphore.acquire();
  46.                 System.out.println(name + " got permit for book");
  47.  
  48.                 Book book = books.get(0);
  49.                 books.remove(0);
  50.                 System.out.println(name + " got " + book);
  51.  
  52.                 try {
  53.                     Thread.sleep(2000);
  54.                 } finally {
  55.                     books.add(book);
  56.                     System.out.println(name + " returned " + book.name);
  57.                    
  58.                     semaphore.release();
  59.                 }
  60.  
  61.             } catch (InterruptedException e) {
  62.                 e.printStackTrace();
  63.             }
  64.         }
  65.     }
  66.    
  67.     static class Book {
  68.         public String name;
  69.  
  70.         public Book(String name) {
  71.             this.name = name;
  72.         }
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement