The following program demonstrates the use of a lock.
It creates two threads that access a shared resource.
import java.util.concurrent.locks.ReentrantLock; public class Main { public static void main(String args[]) { ReentrantLock lock = new ReentrantLock(); new LockThread(lock, "A"); new LockThread(lock, "B"); }//ww w . ja v a 2s . com } // A shared resource. class MyValue { static int count = 0; } // A thread of execution that increments count. class LockThread implements Runnable { private String name; private ReentrantLock lock; public LockThread(ReentrantLock lk, String n) { lock = lk; name = n; new Thread(this).start(); } public void run() { System.out.println("Starting " + name); try { // First, lock count. System.out.println(name + " is waiting to lock count."); lock.lock(); System.out.println(name + " is locking count."); MyValue.count++; System.out.println(name + ": " + MyValue.count); // Now, allow a context switch -- if possible. System.out.println(name + " is sleeping."); Thread.sleep(1000); } catch (InterruptedException exc) { System.out.println(exc); } finally { // Unlock System.out.println(name + " is unlocking count."); lock.unlock(); } } }