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 VolleyballTournament {
- static Semaphore sala = null;
- static Semaphore soblekuvalna = null;
- static int count = 0;
- static Semaphore cLock = null;
- static Semaphore canPlay = null;
- public static void init() {
- sala = new Semaphore(12);
- soblekuvalna = new Semaphore(4);
- cLock = new Semaphore(1);
- canPlay = new Semaphore(0);
- }
- public static class Player extends TemplateThread{
- public Player(int numRuns) {
- super(numRuns);
- // TODO Auto-generated constructor stub
- }
- 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();
- cLock.acquire();
- count++;
- System.out.println("In dressing room.");
- Thread.sleep(10);// this represent the dressing time
- if(count==4) {
- canPlay.release(4);
- soblekuvalna.release(4);
- count=0;
- }
- cLock.release();
- 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
- System.out.println("Player done.");
- sala.release();
- cLock.acquire();
- count--;
- if(count==1) {
- System.out.println("Game finished.");
- }
- // only one player should print the next line, representing that the game has finished
- cLock.release();
- }
- }
- 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
- init();
- 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(2_000);
- //t.interrupt(); HACK
- }
- // 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.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement