AtomicBoolean运用

首先先看如下例子 
 1  private static class BarWorker implements Runnable {

 2 

 3   private static boolean exists = false;

 4 

 5   private String name;

 6 

 7   public BarWorker(String name) {

 8    this.name = name;

 9   }

10 

11   public void run() {

12    if (!exists) {

13     exists = true;

14     System.out.println(name + " enter");

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

16     System.out.println(name + " leave");

17     exists = false;

18    } else {

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

20    }

21   }

22 

23  }
View Code

static变量exists用来实现同一时间只有一个worker在工作. 但是假设exists的判断和exists = true;之间有了 
其他指令呢 

 

 

 1  private static class BarWorker implements Runnable {

 2 

 3   private static boolean exists = false;

 4 

 5   private String name;

 6 

 7   public BarWorker(String name) {

 8    this.name = name;

 9   }

10 

11   public void run() {

12    if (!exists) {

13     try {

14      TimeUnit.SECONDS.sleep(1);

15     } catch (InterruptedException e1) {

16      // do nothing

17     }

18     exists = true;

19     System.out.println(name + " enter");

20     try {

21      System.out.println(name + " working");

22      TimeUnit.SECONDS.sleep(2);

23     } catch (InterruptedException e) {

24      // do nothing

25     }

26     System.out.println(name + " leave");

27     exists = false;

28    } else {

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

30    }

31   }

32 

33  }
View Code

 

  

这时输出是 
bar2 enter 
bar2 working 
bar1 enter 
bar1 working 
bar1 leave 
bar2 leave 
看到两个线程同时工作了. 
这时可以用AtomicBoolean 

 

 1 private static class BarWorker implements Runnable {

 2 

 3   private static AtomicBoolean exists = new AtomicBoolean(false);

 4 

 5   private String name;

 6 

 7   public BarWorker(String name) {

 8    this.name = name;

 9   }

10 

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{

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

24    }

25   }

26 

27  }
View Code
因为它提供了原子性操作,其中exists.compareAndSet(false, true)这个操作把比较和赋值操作组成了一个原子操作,
中间不会提供可乘之机.输出为 
bar1 enter 
bar1 working 
bar2 give up

 

 

你可能感兴趣的:(boolean)