In the code below, I have a class LearnNumbers that is using an object of another class.
I would like to synchronize LearnNumbers using the keyword synchronized such that only one
thread can execute the methods at a point of time and the entire method learn is not synchronized together. Rather, only the lines of code where num is being accessed, should be synchronized.How ould I achieve this?
class LearnNumbers
{
Numbers num = new Numbers();
public void learn()
{
if(num == 1)
num.printOne();
else if(num == 2)
num.printTwo();
else
num.printThree();
}
}
class Numbers
{
public void printOne()
{
System.out.println("You are printing One");
}
public void printTwo()
{
System.out.println("You are printing Two");
}
public void printThree()
{
System.out.println("You are printing Three");
}
}