CIS 260 Reentrant locksOne of the newer features of Java concurrency is the ReentrantLock class. It essentially lets us write code similar to synchronized code blocks. Note that threads waiting on a lock will not be treated fairly when being started back up. One thread may get several turns before another thread gets any turns. If you want to guarantee fairness, you can pass the value true to the ReentrantLock constructor - but be advised that fairness comes at a cost to efficiency. import java.util.concurrent.locks.*; public class TThread8b { public static void main(String[] args) { Adder t = new Adder(); t.start(); (new TestSync(t)).start(); t = null; } } class Adder extends Thread { private ReentrantLock myLock = new ReentrantLock(); private int count1 = 0, count2 = 0, count3 = 0; private boolean done = false; private String[] sym = { "-", "\\", "|", "/" }; public void run() { int countHolder = 0; while (count1 <= 100) { myLock.lock(); try { countHolder = count1++; count2++; count3++; } finally { myLock.unlock(); } System.out.print("\r" + sym[countHolder % 4]); try { Thread.sleep(50); } catch (InterruptedException e) { System.out.println("Application Interrupted"); } } done = true; } public boolean check() { int c1, c2, c3; myLock.lock(); try { c1 = count1; c2 = count2; c3 = count3; } finally { myLock.unlock(); } if ((c1 != c2) || (c2 != c3)) System.out.println("\rNot synced: " + c1 + ", " + c2 + ", " + c3); return !done; } } class TestSync extends Thread { private int totAccess = 0; private Adder t1 = null; public TestSync(Adder t) { t1 = t; } public void run() { while (t1.check()) ++totAccess; System.out.println("\nTotal sync accesses: " + totAccess); } } // - // Total sync accesses: 114036512 |