Question: PLEASE comment on each line of this code, explaining what every line does. import java.util.Random; import java.util.concurrent.Semaphore; public class l { public static void main(String[]

PLEASE comment on each line of this code, explaining what every line does.


import java.util.Random; import java.util.concurrent.Semaphore;

public class l { public static void main(String[] args) { Semaphore ball = new Semaphore(1); Thread red = new Thread(new Team("Red", ball)); Thread blue = new Thread(new Team("Blue", ball)); Thread white = new Thread(new Team("White", ball)); red.start(); blue.start(); white.start(); } }

class Team implements Runnable { private String name; private Semaphore ball; private Random random = new Random();

public Team(String name, Semaphore ball) { this.name = name; this.ball = ball; }

@Override public void run() { for (int i = 1; i <= 3; i++) { try { Thread.sleep(random.nextInt(1000)); System.out.println(name + " team wants the ball. Turn #" + i); ball.acquire(); System.out.println(name + " team is playing with ball. Turn #" + i); Thread.sleep(random.nextInt(1000)); System.out.println(name + " team is done playing with ball. Turn #" + i); ball.release(); } catch (InterruptedException e) { e.printStackTrace(); } } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!