You do this by applying the synchronized
keyword to the method,
like this:
public class SychronizedCounter extends Counter {
public synchronized void count() {
int limit = i + 100;
while (i++ != limit) System.out.println(i);
}
}
However you don't want to synchronize lightly.
This solution severely impacts performance. In general synchronized methods run three to ten times slower that the equivalent non-synchronized method. Synchronization is not a panacea, either. There can still be thread related bugs in classes that have synchronized methods. There can also be non-thread related bugs. In fact there's one in this very class. Can you find it?