i
and a print method. Since i
is a static variable, there is a chance that a different instance of this class in a different method might change i
before youšre finished printing. The synchronized keyword guarantees that no more than one instance of this method is going to run at once so i wonšt suddenly be changed from 5 to 17 while the for loop is executing.
public class SynchronizedPrinter {
static int i = 0;
public synchronized void print() {
for (i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}