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 If count is already at its maximum
of then it waits until count is less than before incrementing it The other method decrement
attempts to decrement count by If count is already at its minimum of then it waits until count is
greater than 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 and
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 times. In between each
call, it sleeps for a random amount of time between and milliseconds and the other thread calls the
Counter's decrement method times. In between each call, it sleeps for a random amount of time
between and 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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
