写点什么

AtomicBoolean 介绍与使用

  • 2021 年 11 月 10 日
  • 本文字数:1173 字

    阅读完需:约 4 分钟

  1. ?????private?static?boolean?exists?=?false;????

  2. ?????private?String?name;????

  3. ?????public?BarWorker(String?name)?{?????

  4. ??????????this.name?=?name;????

  5. ?????}????

  6. ?????@Override????

  7. ?????public?void?run()?{?????

  8. ?????????if?(!exists)?{????

  9. ?????????????????try?{????

  10. ??????????????????TimeUnit.SECONDS.sleep(1);????

  11. ?????????????????}?catch?(InterruptedException?e1)?{????

  12. ??????????????????//?do?nothing????

  13. ?????????????????}????

  14. ?????????????????exists?=?true;????

  15. ?????????????????System.out.println(name?+?"?enter");????

  16. ?????????????????try?{????

  17. ??????????????????System.out.println(name?+?"?working");????

  18. ??????????????????TimeUnit.SECONDS.sleep(2);????

  19. ?????????????????}?catch?(InterruptedException?e)?{????

  20. ??????????????????//?do?nothing????

  21. ?????????????????}????

  22. ?????????????????System.out.println(name?+?"?leave");????

  23. ?????????????????exists?=?false;????

  24. ????????}?else?{????

  25. ?????????System.out.println(name?+?"?give?up");????

  26. ????????}????

  27. ????}???

  28. ?????public?static?void?main(String[]?args)?{??

  29. ?????????BarWorker?bar1?=?new?BarWorker("bar1");??

  30. ?????????BarWorker?bar2?=?new?BarWorker("bar2");??

  31. ?????????new?Thread(bar1).start();??

  32. ?????????new?Thread(bar2).start();??

  33. ????}??

  34. }??


该代码使用 static 变量 exists 用来实现同一时间只有一个 worker 在工作. 但是假设 exists 的判断和 exists = true;之间有了 其他指令呢? 输出如下:


[html]? view plain ?copy


  1. bar1?enter??

  2. bar2?enter??

  3. bar1?working??

  4. bar2?working??

  5. bar1?leave??

  6. bar2?leave??


可以看到两个线程同时工作了。这时可以用 AtomicBoolean 进行线程同步,代码如下:


[html]? view plain ?copy


  1. package?zmx.atomic.test;??

  2. import?java.util.concurrent.TimeUnit;??

  3. import?java.util.concurrent.atomic.AtomicBoolean;??

  4. public?class?BarWorker2?implements?Runnable?{??

  5. ????private?static?AtomicBoolean?exists?=?new?AtomicBoolean(false);????

  6. ?????private?String?name;????

  7. ?????public?BarWorker2(String?name)?{?????

  8. ??????????this.name?=?name;????

  9. ?????}????

  10. ?????@Override????

  11. ?????public?void?run()?{?????

  12. ?????????if?(exists.compareAndSet(false,?true))?{????

  13. ?????????????System.out.println(name?+?"?enter");????

  14. ?????????????try?{????

  15. ??????????????????System.out.println(name?+?"?working");????

  16. ??????????????????TimeUnit.SECONDS.sleep(2);????

  17. ?????????????}?catch?(InterruptedException?e)?{????

  18. ??????????????????//?do?nothing????

  19. ?????????????}????

  20. ?????????????System.out.println(name?+?"?leave");????

  21. ?????????????exists.set(false);??????

  22. ????????}?else?{????

评论

发布
暂无评论
AtomicBoolean介绍与使用