首页 > 代码库 > AtomicBoolean运用
AtomicBoolean运用
AtomicBoolean运用
首先先看如下例子
Java代码
- private static class BarWorker implements Runnable {
- private static boolean exists = false;
- private String name;
- public BarWorker(String name) {
- this.name = name;
- }
- public void run() {
- if (!exists) {
- exists = true;
- System.out.println(name + " enter");
- System.out.println(name + " working");
- System.out.println(name + " leave");
- exists = false;
- } else {
- System.out.println(name + " give up");
- }
- }
- }
static变量exists用来实现同一时间只有一个worker在工作. 但是假设exists的判断和exists = true;之间有了
其他指令呢
Java代码
- private static class BarWorker implements Runnable {
- private static boolean exists = false;
- private String name;
- public BarWorker(String name) {
- this.name = name;
- }
- public void run() {
- if (!exists) {
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e1) {
- // do nothing
- }
- exists = true;
- System.out.println(name + " enter");
- try {
- System.out.println(name + " working");
- TimeUnit.SECONDS.sleep(2);
- } catch (InterruptedException e) {
- // do nothing
- }
- System.out.println(name + " leave");
- exists = false;
- } else {
- System.out.println(name + " give up");
- }
- }
- }
这时输出是
bar2 enter
bar2 working
bar1 enter
bar1 working
bar1 leave
bar2 leave
看到两个线程同时工作了.
这时可以用AtomicBoolean
Java代码
- private static class BarWorker implements Runnable {
- private static AtomicBoolean exists = new AtomicBoolean(false);
- private String name;
- public BarWorker(String name) {
- this.name = name;
- }
- public void run() {
- if (exists.compareAndSet(false, true)) {
- System.out.println(name + " enter");
- try {
- System.out.println(name + " working");
- TimeUnit.SECONDS.sleep(2);
- } catch (InterruptedException e) {
- // do nothing
- }
- System.out.println(name + " leave");
- exists.set(false);
- }else{
- System.out.println(name + " give up");
- }
- }
- }
因为它提供了原子性操作,其中exists.compareAndSet(false, true)这个操作把比较和赋值操作组成了一个原子操作,
中间不会提供可乘之机.输出为
bar1 enter
bar1 working
bar2 give up
AtomicBoolean运用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。