Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.concurrent.Semaphore;
- public class VoleyballTournament {
- public static void main(String[] args) throws InterruptedException {
- HashSet<Player> threads = new HashSet<>();
- for (int i = 0; i < 60; i++) {
- Player p = new Player(i);
- threads.add(p);
- }
- // run all threads in background
- for (Player t: threads)
- {
- t.start();
- }
- // after all of them are started, wait each of them to finish for maximum 2_000 ms
- for(Player t: threads)
- {
- t.join(2000);
- }
- // for each thread, terminate it if it is not finished
- for (Player t: threads) {
- if (t.isAlive()) {
- t.interrupt();
- System.out.println("Possible deadlock");
- }
- }
- System.out.println("Tournament finished.");
- }
- }
- class Player extends Thread {
- int tdx;
- static Semaphore sala=new Semaphore(12);
- static Semaphore soblekuvalna=new Semaphore(4);
- static int count=0;
- static int gCount=0;
- static Semaphore clock=new Semaphore(1);
- static Semaphore canPlay=new Semaphore(0);
- static Semaphore eHall=new Semaphore(0);
- static boolean flag=false;
- public Player(int tdx)
- {
- this.tdx=tdx;
- }
- public void execute() throws InterruptedException {
- // at most 12 players should print this in parallel
- sala.acquire();
- System.out.println("Player inside.");
- // at most 4 players may enter in the dressing room in parallel
- soblekuvalna.acquire();
- System.out.println("In dressing room.");
- clock.acquire();
- count++;
- gCount++;
- if(count==4)
- {
- count=0;
- eHall.release(4);
- flag=true;
- }
- Thread.sleep(10);// this represent the dressing time
- if(gCount==12)canPlay.release(12);
- if(flag)
- {
- soblekuvalna.release(4);
- flag=false;
- }
- clock.release();
- eHall.acquire();
- canPlay.acquire();
- // after all players are ready, they should start with the game together
- System.out.println("Game started.");
- Thread.sleep(100);// this represent the game duration
- clock.acquire();
- --gCount;
- if(gCount==0)
- {
- System.out.println("game finished");
- sala.release(12);
- eHall.drainPermits();
- canPlay.drainPermits();
- count =0;
- }
- else {
- System.out.println("Player done.");
- }// only one player should print the next line, representing that the game has finished
- clock.release();
- }
- public void run()
- {
- try
- {
- execute();
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement