126k views
3 votes
I have a class named Counter. In this class I have a synchronized method called countRange(). This method prints out a count in the range from the minimum to the maximum values stored by the Counter class attributes. Please implement the body of the main() method in Test class to instantiate and start two threads that invoke countRange() method. You can use either named or anonymous Thread instances. Don't forget to make a call to start() method in each thread. What I am asking you to do is similar to what Stopwatch examples in the "Multi-threading and concurrent programming" lecture module showed.

Please only include the code inside the main() method into your answer.
Below is the implementation of Counter class and the shell of the main() method in Test class:
import java.lang.*;
class Counter {
private int min;
private int max;
Counter(int min, int max){
this.min = min;
this.max = max;
}
synchronized public void countRange() {
for(int i = this.min; i <= this.max; i++){
System.out.println(i);
}
}
}
public class Test {
public static void main(String[]args) {
// your implementation goes here
}
}

User IShaalan
by
4.2k points

1 Answer

2 votes

Answer:

Following are the code to this question:

Counter T = new Counter(1, 100); //creating Counter class object and call its parameterized constructor

Thread T1 = new Thread(new Runnable() //creating Thread object T1.

{

public void run() //define run method

{

T.countRange(); //call countRange method

}

});

Thread T2 = new Thread(new Runnable() //creating another object "T2" of Thread.

{

public void run() //define run method

{

T.countRange(); //call countRange method

}

});

T1.start(); //start Thread T1

T2.start(); //start Thread T2

Step-by-step explanation:

Description of the above code as follows:

  • In the given code, inside the main method the Counter class object "T" is created, that calls its parameterized constructor, which accepts two integer value that is "1 and 100".
  • In the next step, thread class object T1 and T2, is created, which uses run method, in which it called the countRange method inside the method a for loop is declared that prints value between parameter value.
  • In the last step, the start method is called, which uses the run method to call countRange method.
  • For full program code please find the attachment.
I have a class named Counter. In this class I have a synchronized method called countRange-example-1
User Tony Hopkinson
by
4.8k points