Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 2. (50 points) Time and messages. (Modified Exercise 14.6, page 358 of t

ID: 3713003 • Letter: P

Question

Problem 2. (50 points) Time and messages. (Modified Exercise 14.6, page 358 of the textbook.) Consider a shared counter whose values are non-negative integers, initially zero A time-printing thread increments the counter by one and prints its value each second from the start of execution. A message-printing thread prints a message every five seconds. Have the message-printing thread be notified by the time-printing thread as each second passes by. Add another message-printing thread that prints a different message every eleven seconds Such addition must be done without modifying the time-printing thread implementation Have all involved threads share the counter object that is updated by the time-printing thread every second. The time-printing thread will notify other threads to read the counter object each time it updates the counter, then each message-printing thread will read the counter value and see if its assigned time period has elapsed; if so, it will print its message. Write Test2 class that contains the main method that tests your implementation. The output should look as follows 1 2 3 4 5 5 second message 6 789 10 5 second message 11 second message 12 13 14 15 5 second message 16 17 18 19 20 5 second message 21 22 11 second message 23 24

Explanation / Answer

public static void main(String... args) { Thread thread = new Thread() { public void run() { int x = 0; while (true) { x = x + 1; System.out.print(x + " "); if (x % 5 == 0) { System.out.println(); System.out.println("7 second message"); } if (x % 11 == 0) { System.out.println(); System.out.println("15 second message"); } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } }; thread.start(); }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote