并发编程——按顺序打印(AtomicInteger类)

AtomicInteger类:

高并发的情况下,i++无法保证原子性,往往会出现问题,所以引入AtomicInteger类。并发编程中的原子性问题

AtomicInteger类工具方法:

private static AtomicInteger atomicInteger = new AtomicInteger();

// 获取当前值
public static void getCurrentValue(){}
// 设置value值
public static void setValue(){}
// 先获取旧值,然后设置新值
public static void getAndSet(){}
// 先获取旧值,然后再自增
public static void getAndIncrement(){}
// 先获取旧值,然后再自减
public static void getAndDecrement(){}
// 先获取旧值,然后再加
public static void getAndAdd(){}
// 先加1,然后获取新值
public static void incrementAndGet(){}
// 先减1,然后获取新值
public static void decrementAndGet(){}
// 先增加,然后获取值
public static void addAndGet(){}

顺序打印的使用:

class Foo {

  private AtomicInteger firstJobDone = new AtomicInteger(0);
  private AtomicInteger secondJobDone = new AtomicInteger(0);

  public Foo() {}

  public void first(Runnable printFirst) throws InterruptedException {
    // printFirst.run() outputs "first".
    printFirst.run();
    // mark the first job as done, by increasing its count.
    firstJobDone.incrementAndGet();
  }

  public void second(Runnable printSecond) throws InterruptedException {
    while (firstJobDone.get() != 1) {
      // waiting for the first job to be done.
    }
    // printSecond.run() outputs "second".
    printSecond.run();
    // mark the second as done, by increasing its count.
    secondJobDone.incrementAndGet();
  }

  public void third(Runnable printThird) throws InterruptedException {
    while (secondJobDone.get() != 1) {
      // waiting for the second job to be done.
    }
    // printThird.run() outputs "third".
    printThird.run();
  }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值