import java.util.HashSet;
import java.util.concurrent.Semaphore;
public class BasketballTournament {
public static void main(String[] args) {
HashSet threads = new HashSet<>();
for (int i = 0; i < 100; i++) {
Player p = new Player();
threads.add(p);
}
// run all threads in background
for(Player p : threads) {
p.start();
}
// after all of them are started, wait each of them to finish for maximum 5_000 ms
for(Player p : threads) {
try {
p.join(5000);
}
catch (InterruptedException e) {
}
}
// for each thread, terminate it if it is not finished
for(Player p : threads) {
if(p.isAlive()) {
System.out.println("Possible deadlock!");
return;
}
}
System.out.println("Tournament finished.");
}
}
class Player extends Thread {
static Semaphore sala = new Semaphore(20);
static Semaphore soblekuvalna = new Semaphore(0);
static int igraci_vo_salata = 0;
void enter_sala() throws InterruptedException{
sala.acquire();
soblekuvalna.release();
}
void exit_sala() {
sala.release();
}
void enter_soblekuvalna() throws InterruptedException{
soblekuvalna.acquire();
}
void exit_soblekuvalna() {
soblekuvalna.release();
}
public void execute() throws InterruptedException {
// at most 20 players should print this in parallel
enter_sala();
System.out.println("Player inside.");
// at most 10 players may enter in the dressing room in parallel
enter_soblekuvalna();
System.out.println("In dressing room.");
Thread.sleep(10);// this represent the dressing time
// after all players are ready, they should start with the game together
exit_soblekuvalna();
System.out.println("Game started.");
Thread.sleep(100);// this represent the game duration
System.out.println("Player done.");
exit_sala();
// only one player should print the next line, representing that the game has finished
synchronized (Player.class) {
igraci_vo_salata++;
if (igraci_vo_salata == 20) {
System.out.println("Game finished.");
igraci_vo_salata = 0;
}
}
}
@Override
public void run() {
try {
execute();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}