1 4 package com.tc.test; 5 6 import EDU.oswego.cs.dl.util.concurrent.CyclicBarrier; 7 8 public class BitChangeNotReflected extends TCTestCase { 9 10 private static final byte INITIAL = 0x01; 11 private static final int LOOP_COUNT = 50000; 12 13 public void testBitChangeNotReflected() throws Exception { 14 BitData data = new BitData(); 15 Object lock = new Object (); 16 CyclicBarrier barrier = new CyclicBarrier(2); 17 Thread t1 = new Changer(data, lock, barrier); 18 Thread t2 = new Reader(data, lock, barrier); 19 t1.start(); 20 t2.start(); 21 try { 22 t1.join(); 23 t2.join(); 24 } catch (InterruptedException e) { 25 throw new RuntimeException (e); 26 } 27 } 28 29 public static byte shiftRightRotate(byte f) { 30 byte f1 = (byte) (f >> 1); 31 return (byte) (f1 == 0x00 ? 0x80 : f1); 32 } 33 34 static class Changer extends Thread { 35 36 private final BitData data; 37 private final Object lock; 38 private final CyclicBarrier barrier; 39 40 public Changer(BitData data, Object lock, CyclicBarrier barrier) { 41 this.data = data; 42 this.lock = lock; 43 this.barrier = barrier; 44 } 45 46 public void run() { 47 try { 48 run2(); 49 } catch (Exception e) { 50 throw new RuntimeException (e); 51 } 52 } 53 54 public void run2() throws Exception { 55 int count = LOOP_COUNT; 56 while (count-- > 0) { 57 barrier.barrier(); 58 synchronized (lock) { 59 data.shiftRightRotate(); 60 } 61 } 62 } 63 64 } 65 66 static class Reader extends Thread { 67 68 private final BitData data; 69 private final Object lock; 70 private final CyclicBarrier barrier; 71 72 public Reader(BitData data, Object lock, CyclicBarrier barrier) { 73 this.data = data; 74 this.lock = lock; 75 this.barrier = barrier; 76 } 77 78 public void run() { 79 try { 80 run2(); 81 } catch (Exception e) { 82 throw new RuntimeException (e); 83 } 84 } 85 86 public void run2() throws Exception { 87 byte local = INITIAL; 88 int count = LOOP_COUNT; 89 while (count-- > 0) { 90 local = shiftRightRotate(local); 91 synchronized (lock) { 92 data.isEqual(local); 93 } 94 barrier.barrier(); 95 } 96 97 } 98 99 } 100 101 static class BitData { 102 int i; 103 byte flag = INITIAL; 104 105 void shiftRightRotate() { 106 flag = BitChangeNotReflected.shiftRightRotate(flag); 107 } 108 109 boolean isEqual(byte f) { 110 return (flag == f); 111 } 112 113 byte getFlag() { 114 return flag; 115 } 116 117 } 118 119 } 120 | Popular Tags |