|
| 1 | +package threadsecurity; |
| 2 | + |
| 3 | +import java.util.concurrent.BrokenBarrierException; |
| 4 | +import java.util.concurrent.CyclicBarrier; |
| 5 | +import java.util.concurrent.atomic.AtomicInteger; |
| 6 | + |
| 7 | +/** |
| 8 | + * 1.运行结果出错 |
| 9 | + * 计数不准确,并且找出具体出错的位置 |
| 10 | + * |
| 11 | + * @Author: zzStar |
| 12 | + * @Date: 10-18-2020 19:38 |
| 13 | + */ |
| 14 | +public class MultiThreadError implements Runnable { |
| 15 | + |
| 16 | + int index = 0; |
| 17 | + |
| 18 | + static AtomicInteger realIndex = new AtomicInteger(); |
| 19 | + static AtomicInteger wrongCount = new AtomicInteger(); |
| 20 | + |
| 21 | + // 等待共同出发 |
| 22 | + static volatile CyclicBarrier cyclicBarrier1 = new CyclicBarrier(2); |
| 23 | + static volatile CyclicBarrier cyclicBarrier2 = new CyclicBarrier(2); |
| 24 | + |
| 25 | + final boolean[] marked = new boolean[30000]; |
| 26 | + |
| 27 | + static MultiThreadError multiThreadError = new MultiThreadError(); |
| 28 | + |
| 29 | + public static void main(String[] args) throws InterruptedException { |
| 30 | + Thread thread1 = new Thread(multiThreadError); |
| 31 | + Thread thread2 = new Thread(multiThreadError); |
| 32 | + thread1.start(); |
| 33 | + thread2.start(); |
| 34 | + // 使得主线程等待两个子线程停止 |
| 35 | + thread1.join(); |
| 36 | + thread2.join(); |
| 37 | + System.out.println("表面上运行的结果" + multiThreadError.index);//<20000 |
| 38 | + System.out.println("真正运行的次数" + realIndex.get()); |
| 39 | + System.out.println("错误运行的次数" + wrongCount.get()); |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + @Override |
| 44 | + public void run() { |
| 45 | +/* |
| 46 | + while (index < 1000) { |
| 47 | + index++; |
| 48 | + } |
| 49 | +*/ |
| 50 | + marked[0] = true; |
| 51 | + |
| 52 | + for (int i = 0; i < 10000; i++) { |
| 53 | + |
| 54 | + // 两个线程都到await才继续 |
| 55 | + try { |
| 56 | + cyclicBarrier2.reset(); |
| 57 | + cyclicBarrier1.await(); |
| 58 | + } catch (InterruptedException | BrokenBarrierException e) { |
| 59 | + e.printStackTrace(); |
| 60 | + } |
| 61 | + |
| 62 | + index++; |
| 63 | + |
| 64 | + // 都++后就才继续 |
| 65 | + try { |
| 66 | + cyclicBarrier1.reset(); |
| 67 | + cyclicBarrier2.await(); |
| 68 | + } catch (InterruptedException | BrokenBarrierException e) { |
| 69 | + e.printStackTrace(); |
| 70 | + } |
| 71 | + |
| 72 | + // 原子操作下准确的值 |
| 73 | + realIndex.incrementAndGet(); |
| 74 | + |
| 75 | + // 这里需要同步,确保不被打断,并且保证可见性 |
| 76 | + synchronized (multiThreadError) { |
| 77 | + |
| 78 | + // 前一位也必须是true |
| 79 | + if (marked[index] && marked[index - 1]) { |
| 80 | + System.out.println("发生错误已被标记" + index); |
| 81 | + // 发生的错误数也增加 |
| 82 | + wrongCount.incrementAndGet(); |
| 83 | + } |
| 84 | + |
| 85 | + // 存进marked,标记 |
| 86 | + marked[index] = true; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +} |
0 commit comments