TThread5b.java
Select all
import java.util.concurrent.locks.*; public class TThread5b { boolean done = false; private int count1 = 0, count2 = 0, count3 = 0; private void init() { final ReentrantLock l = new ReentrantLock(); class Adder extends Thread { public void run() { while (count1 <= 100) { l.lock(); count1++; count2++; count3++; l.unlock(); try{ Thread.sleep(50); } catch (InterruptedException e) { System.out.println("Application Interrupted"); } } done = true; } } class TestSync extends Thread { private int totAccess = 0; public void run() { int c1, c2, c3; while (!done) { totAccess++; l.lock(); // use the try/catch/finally form if any // execptions could happen - not needed // in this case try { c1 = count1; c2 = count2; c3 = count3; } finally { l.unlock(); } if ((c1 != c2) || (c2 != c3)) { System.out.println("\rNot synced: " + c1 + ", " + c2 + ", " + c3); } } System.out.println("Total sync accesses: " + totAccess); } } (new Adder()).start(); (new TestSync()).start(); } public static void main(String[] args) { TThread5b app = new TThread5b(); app.init(); } }