Question: Write a Java program to create a Counter class with a private count instance variable and two methods. The first method increment ( ) tries

Write a Java program to create a Counter class with a private count instance variable and two
methods. The first method increment() tries to increments count by 1. If count is already at its maximum
of 3, then it waits until count is less than 3 before incrementing it. The other method decrement()
attempts to decrement count by 1. If count is already at its minimum of 0, then it waits until count is
greater than 0 before decrementing it. Every time either method has to wait, it displays a statement saying
why it is waiting. Also, every time an increment or decrement occurs, the counter displays a statement
that says what occurred and shows count's new value.
Demonstrates how two synchronized methods need to communicate to keep a counter between 0 and 3
when one thread repeatedly tries to increase the counter and the other thread repeatedly tries to
decrease the counter. One thread class calls the Counter's increment() method 20 times. In between each
call, it sleeps for a random amount of time between 0 and 500 milliseconds and the other thread calls the
Counter's decrement() method 20 times. In between each call, it sleeps for a random amount of time
between 0 and 500 milliseconds.
Write a CounterDemo class with a main() method that creates one Counter and the two threads and
starts the threads running. Create just one thread class by implementing Runnable interface that either
increments or decrements the counter, depending on a parameter passed to the thread class's
constructor . Make sure that the main thread ends at the last.

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!