AtomicBoolean 介绍与使用
?????private?static?boolean?exists?=?false;????
?????private?String?name;????
?????public?BarWorker(String?name)?{?????
??????????this.name?=?name;????
?????}????
?????@Override????
?????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");????
????????}????
????}???
?????public?static?void?main(String[]?args)?{??
?????????BarWorker?bar1?=?new?BarWorker("bar1");??
?????????BarWorker?bar2?=?new?BarWorker("bar2");??
?????????new?Thread(bar1).start();??
?????????new?Thread(bar2).start();??
????}??
}??
该代码使用 static 变量 exists 用来实现同一时间只有一个 worker 在工作. 但是假设 exists 的判断和 exists = true;之间有了 其他指令呢? 输出如下:
[html]? view plain ?copy
bar1?enter??
bar2?enter??
bar1?working??
bar2?working??
bar1?leave??
bar2?leave??
可以看到两个线程同时工作了。这时可以用 AtomicBoolean 进行线程同步,代码如下:
[html]? view plain ?copy
package?zmx.atomic.test;??
import?java.util.concurrent.TimeUnit;??
import?java.util.concurrent.atomic.AtomicBoolean;??
public?class?BarWorker2?implements?Runnable?{??
????private?static?AtomicBoolean?exists?=?new?AtomicBoolean(false);????
?????private?String?name;????
?????public?BarWorker2(String?name)?{?????
??????????this.name?=?name;????
?????}????
?????@Override????
?????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?{????
评论