Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.concurrent.Semaphore;
- public class Main {
- static Semaphore semaphore = new Semaphore(4);
- public static void main(String[] args) {
- System.out.println("Max 4 books");
- StudentThread t1 = new StudentThread("1 Student");
- StudentThread t2 = new StudentThread("2 Student");
- StudentThread t3 = new StudentThread("3 Student");
- StudentThread t4 = new StudentThread("4 Student");
- StudentThread t5 = new StudentThread("5 Student");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- static class StudentThread extends Thread {
- private String name = "";
- public StudentThread(String name) {
- this.name = name;
- }
- @Override
- public void run() {
- super.run();
- try {
- System.out.println(name + " : lock");
- System.out.println("Available books: " + semaphore.availablePermits());
- semaphore.acquire();
- System.out.println(name + " got permit for book");
- // method for get book from db
- try {
- Thread.sleep(2000);
- } finally {
- System.out.println(name + " book returned");
- // method for return book
- semaphore.release();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement