Java7新特性(四)并发 5 CopyOnWriteArrayList对象

本文主要根据《Java程序员修炼之道》整理的代码笔记片段

CopyOnWriteArrayList对象  增加写时复制,快速一致的快照  【每个读取器性能,自身一致性的快照】 

(不完美同步,非关键任务,修改次数与读取次数相差大)

public class MicroBlogTimeline {
  private final CopyOnWriteArrayList<Update> updates;
  //增加写时复制,快速一致的快照  【每个读取器性能,自身一致性的快照】 (不完美同步,非关键任务,修改次数与读取次数相差大)
  
  private final Lock lock;
  private final String name;
  private Iterator<Update> it;

  public MicroBlogTimeline(String name_) {
    name = name_;
    updates = new CopyOnWriteArrayList<>();
    lock = new ReentrantLock();
  }

  MicroBlogTimeline(String name_, CopyOnWriteArrayList<Update> l_, Lock lock_) {
    name = name_;
    updates = l_;
    lock = lock_;
  }

  public void addUpdate(Update update_) {
    updates.add(update_);
  }

  public void prep() {
    it = updates.iterator();
  }

  public void printTimeline() {
    lock.lock();
    try {
      if (it != null) {
        System.out.print(name + ": ");
        while (it.hasNext()) {
          Update s = it.next();
          System.out.print(s + ", ");
        }
        System.out.println();
      }
    } finally {
      lock.unlock();
    }
  }
}
public class CopyOnWriteExampleMain {

  public static void main(String[] a) {
    final CountDownLatch firstLatch = new CountDownLatch(1);
    final CountDownLatch secondLatch = new CountDownLatch(1);
    final Update.Builder ub = new Update.Builder();

    final CopyOnWriteArrayList<Update> l = new CopyOnWriteArrayList<>();
    l.add(ub.author(new Author("Ben")).updateText("I like pie").build());
    l.add(ub.author(new Author("Charles")).updateText("I like ham on rye")
        .build());

    Lock lock = new ReentrantLock();
    final MicroBlogTimeline tl1 = new MicroBlogTimeline("TL1", l, lock);
    final MicroBlogTimeline tl2 = new MicroBlogTimeline("TL2", l, lock);

    Thread t1 = new Thread() {
      public void run() {
        l.add(ub.author(new Author("Jeffrey"))
            .updateText("I like a lot of things").build());
        tl1.prep();
        firstLatch.countDown();
        try {
          secondLatch.await();
        } catch (InterruptedException e) {
        }
        tl1.printTimeline();
      }
    };

    Thread t2 = new Thread() {
      public void run() {
        try {
          firstLatch.await();
          l.add(ub.author(new Author("Gavin")).updateText("I like otters")
              .build());
          tl2.prep();
          secondLatch.countDown();
        } catch (InterruptedException e) {
        }
        tl2.printTimeline();
      }
    };
    t1.start();
    t2.start();
  }

}

(只含关键代码)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值