I've got class A which i need for getting the current date and modifying it.
public class A {
private Calendar cal = Calendar.getInstance();
public void change() {
try
{
cal.add(Calendar.MONTH, 1);
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
}
public void print() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
}
}
In my main function, i created an instance of class A and also created two threads : one responsible for changing the date and the other for printing it to the console(using print and change mathods of A)
What I want it to do is to print the new date after each change, however I got the same date being printed.
public class Main {
public static void main(String[] args) throws InterruptedException {
A a = new A();
Thread B = new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 10; i++) {
a.print();
}
}
});
Thread C = new Thread(new Runnable(){
public void run(){
for(int i =0; i<10; i++) {
a.change();
}
}
});
synchronized (a) {
B.start();
C.start();
}
}
}
and the output is like this:
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27