public class Counting {
public static void main(String[]args) throws InterruptedException {
class Counter {
private int count = 0;
public void increment() { ++count; }
public int getCount() {return count; }
}
final Counter counter =new Counter();
class CountingThread extends Thread {
public void run() {
for(intx = 0; x < 10000; ++x)
counter.increment();
}
}
CountingThread t1 = new CountingThread();
CountingThread t2 = new CountingThread();
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(counter.getCount());
}
}
Try running this code, and you’ll get a different answer each time. The last
three times I ran it, I got 13850, 11867, then 12616
class Counter {
private int count = 0;
➤public synchronized void increment() { ++count; }
public int getCount() {return count; }
}