Java:锁定线程时,AtomicBoolean和静态布尔变量之间有什么区别? [英] Java: What is the different between AtomicBoolean and a static boolean variable when locking a thread?

查看:96
本文介绍了Java:锁定线程时,AtomicBoolean和静态布尔变量之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个叫做T的线程类.

I write a thread class called T.

我的目的是确保一次仅运行一个线程对象.

My purpose is to make sure only one thread object running at a time.

因此,在调用线程对象时,它将检查一个称为BUSY的布尔标志.

So when the thread object is called, it would check a boolean flag called BUSY.

我的问题是

private static AtomicBoolean BUSY = new AtomicBoolean(false);

private static boolean BUSY = false;

我认为,如果使用静态",则所有对象将仅检查一个BUSY布尔变量,以确保仅运行一个线程对象.

I thought if using the 'static', all object would only check one BUSY boolean variable so that would make sure only one thread object is running.

推荐答案

您必须至少使布尔变量 volatile 和AtomicBoolean变量 final 生效,可比的解决方案.完成之后,您的用例将没有任何区别.

You must at least make the boolean variable volatile and the AtomicBoolean variable final in order to have a comparable solution. After you do that, there will be no difference for your use case.

如果使用 AtomicBoolean getAndSet compareAndSet 方法,则将产生一个差异,这些方法将一次读取和一次写入操作组合为一个原子整体而言,针对 volatile 而言,它们并不是原子的.

The difference comes about if you use AtomicBoolean's getAndSet or compareAndSet methods, which combine one read and one write action into an atomic whole, wheraas these are not atomic when done against a volatile.

这篇关于Java:锁定线程时,AtomicBoolean和静态布尔变量之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆