import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main3 { public static void main(String[] args) { Runnable task = new MyTask3(); Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); // Will make a call to task.run() } } class MyTask3 implements Runnable { private final Lock lock = new ReentrantLock(); private final int MAX_COUNT = 10000; private int sharedCounter = 0; public void run() { System.out.println("Starting! Shared counter = " + getSharedCounter()); for (int i = 0; i < MAX_COUNT; i++) { lock.lock(); try { sharedCounter = sharedCounter + 1; } finally { lock.unlock(); } } System.out.println("Done! Shared counter = " + getSharedCounter()); } private int getSharedCounter() { lock.lock(); try { return sharedCounter; } finally { lock.unlock(); } } }