Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ispiti.tennisTournament;
- import java.util.HashSet;
- import java.util.concurrent.Semaphore;
- public class TennisTournament {
- static Semaphore redPlayers;
- static Semaphore greenPlayers;
- static int numPlayers;
- static Semaphore protect;
- static Semaphore canPlay;
- static Semaphore finishedPlaying;
- public static void init(){
- redPlayers = new Semaphore(2);
- greenPlayers = new Semaphore(2);
- numPlayers = 0;
- protect = new Semaphore(1);
- canPlay = new Semaphore(0);
- finishedPlaying = new Semaphore(0);
- }
- public static class GreenPlayer extends Thread {
- public void execute() throws InterruptedException {
- // System.out.println("Green player ready");
- greenPlayers.acquire();
- System.out.println("Green player enters field");
- protect.acquire();
- numPlayers++;
- boolean controller = false;
- if(numPlayers == 4){
- controller = true;
- canPlay.release(4);
- }
- protect.release();
- canPlay.acquire();
- System.out.println("Match started");
- Thread.sleep(200);
- System.out.println("Green player finished playing");
- finishedPlaying.release();
- if(controller) {
- finishedPlaying.acquire(4);
- System.out.println("Match finished");
- numPlayers = 0;
- greenPlayers.release(2);
- redPlayers.release(2);
- }
- }
- @Override
- public void run() {
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public static class RedPlayer extends Thread {
- @Override
- public void run() {
- try {
- execute();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public void execute() throws InterruptedException {
- // System.out.println("Red player ready");
- redPlayers.acquire();
- System.out.println("Red player enters field");
- protect.acquire();
- numPlayers++;
- boolean controller = false;
- if(numPlayers == 4){
- controller = true;
- canPlay.release(4);
- }
- protect.release();
- canPlay.acquire();
- System.out.println("Match started");
- Thread.sleep(200);
- System.out.println("Red player finished playing");
- finishedPlaying.release();
- if(controller) {
- finishedPlaying.acquire(4);
- System.out.println("Match finished");
- numPlayers = 0;
- greenPlayers.release(2);
- redPlayers.release(2);
- }
- }
- }
- public static void main(String[] args) throws InterruptedException {
- HashSet<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < 30; i++) {
- RedPlayer red = new RedPlayer();
- threads.add(red);
- GreenPlayer green = new GreenPlayer();
- threads.add(green);
- }
- init();
- // start 30 red and 30 green players in background
- for(Thread t:threads){
- t.start();
- }
- // after all of them are started, wait each of them to finish for 1_000 ms
- for(Thread t:threads){
- t.join();
- }
- // after the waiting for each of the players is done, check the one that are not finished and terminate them
- System.err.println("Uspeshna sinhronizacija");
- }
- }
Add Comment
Please, Sign In to add comment