import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class MyTask implements Runnable { private final int MAX_COUNT = 10000; private final Lock lock = new ReentrantLock(); private int sharedCounter = 0; public void run() { for (int i = 0; i < MAX_COUNT; i++) { lock.lock(); try { sharedCounter = sharedCounter + 1; } finally { lock.unlock(); } } System.out.println("Done! Shared counter = " + sharedCounter); } }