原子操作类AtomicInteger应用案例

有一个按序打印的需求:
我们提供了一个类:

class Foo {
    public void first() { System.out.println("first");  }
    public void second() { System.out.println("second"); }
    public void third() { System.out.println("third"); }
}

三个不同的线程将会共用一个 Foo 实例。

线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法

调用代码如下:

 public static void main(String[] args) {
        Foo foo = new Foo();
        Thread thread1 = new Thread(() -> foo.first());
        Thread thread2 = new Thread(()-> foo.second());
        Thread thread3 = new Thread(()-> foo.third());

        thread3.start();
        thread1.start();
        thread2.start();
    }

某次的执行结果为(顺序不能保证):

third
second
first

请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。确保执行结果为
one
two
three

分析:
三个线程并发执行时,不能确定执行的顺序,可以定义两个AtomicInteger 类型的变量firstJobDone和secondJobDone ,在first()方法执行之后修改firstJobDone的值,只有在firstJobDone值改变以后,才能执行second()方法,second()方法执行之后修改secondJobDone的值,只有secondJobDone 的值改变后,才能执行third()方法。

Java代码如下:

Foo实现类

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();
        firstJobDone.incrementAndGet();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        while (firstJobDone.get() != 1) {
        }
        printSecond.run();
        secondJobDone.incrementAndGet();
    }

    public void third(Runnable printThird) throws InterruptedException {
        while (secondJobDone.get() != 1) {
        }
        printThird.run();
    }
}

main方法如下:

public static void main(String[] args) {
        Foo foo = new Foo();
        Thread thread1 = new Thread(()->{
            try {
                foo.first(()->System.out.println("one"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread2 = new Thread(()->{
            try {
                foo.second(()->System.out.println("two"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread3 = new Thread(() -> {
            try {
                foo.third(() -> System.out.println("three"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread3.start();
        thread1.start();
        thread2.start();
    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值