import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConcurrentProgrammingExample {
private static int counter = 0;
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
incrementCounter();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
incrementCounter();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter: " + counter);
}
private static void incrementCounter() {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
}
}