Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class BasketballTournament {
- public static void main(String[] args) throws InterruptedException {
- Player.init();
- HashSet<Player> threads = new HashSet<>();
- for (int i = 0; i < 100; i++) {
- Player p = new Player();
- threads.add(p);
- }
- // run all threads in background
- for (Thread t : threads)
- t.start();
- // after all of them are started, wait each of them to finish for maximum 5_000 ms
- for (Thread t : threads)
- t.join(5000);
- // for each thread, terminate it if it is not finished
- boolean deadLock = false;
- for (Thread t : threads) {
- if (t.isAlive()) {
- deadLock = true;
- t.interrupt();
- System.out.println("Possible deadlock!");
- }
- }
- if (!deadLock)
- System.out.println("Tournament finished.");
- }
- }
- class Player extends Thread {
- static Semaphore basketballPlayer;
- static Semaphore enterDressingRoom;
- static Semaphore enterField;
- static Semaphore play;
- static Semaphore permitToPlay;
- static Semaphore permitToLeave;
- static Semaphore canBeginEntering;
- static Lock lock = new ReentrantLock();
- static int numPlayersInField = 0;
- static void init() {
- basketballPlayer = new Semaphore(20);
- enterDressingRoom = new Semaphore(10);
- enterField = new Semaphore(20);
- play = new Semaphore(1);
- permitToPlay = new Semaphore(0);
- permitToLeave = new Semaphore(0);
- // Let the next two teams get ready for the match while the previous two are playing
- canBeginEntering = new Semaphore(20);
- }
- public void execute() throws InterruptedException {
- // at most 20 players should print this in parallel
- basketballPlayer.acquire();
- System.out.println("Player inside.");
- // at most 10 players may enter in the dressing room in parallel
- enterDressingRoom.acquire();
- System.out.println("In dressing room.");
- Thread.sleep(10);// this represent the dressing time
- enterDressingRoom.release();
- canBeginEntering.acquire();
- enterField.acquire();
- lock.lock();
- numPlayersInField++;
- lock.unlock();
- if (numPlayersInField == 20) {
- play.acquire();
- permitToPlay.release(19);
- } else {
- permitToPlay.acquire();
- }
- System.out.println("Game started.");
- Thread.sleep(100);// this represent the game duration
- // only one player should print the next line, representing that the game has finished
- lock.lock();
- System.out.println("Player done.");
- numPlayersInField--;
- if (numPlayersInField == 0) {
- System.out.println("Game finished.");
- play.release();
- canBeginEntering.release(20);
- }
- lock.unlock();
- basketballPlayer.release();
- enterField.release();
- }
- @Override
- public void run() {
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment