Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Mobile Communications

Authors: Jochen Schiller

2nd edition

978-0321123817, 321123816, 978-8131724262

More Books

Students also viewed these Programming questions