Boolean值的变化的时候不允许在之间插入,保持操作的原子性

它提供了原子性操作,其中exists.compareAndSet(false, true)这个操作把比较和赋值操作组成了一个原子操作,
中间不会提供可乘之机.输出为

AtomicBoolean 高效并发处理 “只初始化一次”

可以让一个线程等待另一个线程完成任务后再执行:

    public static void main(String[] args) {
Thread t2 = new Thread(new BarWorker("bb"));
Thread t1 = new Thread(new BarWorker("aa"));
t2.run();
t1.run();
} 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)) {
// 当第一个线程设置为true后,另外的线程是进不来的
System.out.println(name + " enter" + "currentvalue=" + exists.get());
try {
System.out.println(name + " working");
Thread.sleep(2000);
} catch (InterruptedException e) {
// do nothing
}
System.out.println(name + " leave");
exists.set(false);
} else {
System.out.println(name + " give up");
}
}
}

thread_AtomicBoolean的更多相关文章

随机推荐

  1. phpMyAdmin在Mac OS X上的配置和使用

    本文主要记录phpMyAdmin在Mac OS X上的配置和使用,避免朋友们走弯路,浪费不必要的时间.   1. 下载:    2. 在"设置"中打开" web shar ...

  2. [转] IE6中请求莫名中断

    这两天碰到的问题,IE6下某个js生成的a节点,设置了href="javascript:;",点击时触一个ajax请求,但在IE6下就是无法执行succese里的内容,所以就用se ...

  3. Quartz 2D绘制简单图形

    在Quartz 2D中,绘图是通过图形上下文进行绘制的,以下绘制几个简单的图形 首先先创建一个QuartzView.swift文件继承自UIView,然后实现drawRect方法: import UI ...

  4. X509证书中RSA公钥的提取与载入

    原文链接: http://blog.chinaunix.net/uid-16515626-id-2741894.html   由于项目需要,我计划利用openssl开发一个基本的CA,实现证书的发放等 ...

  5. Tips for thrift

    Introduction I have designed and developed game servers successfully with thrift (http://thrift.apac ...

  6. WPF常用控件样式集锦

    1.不规则形状按钮(通过更改path实现) <Style x:Key="ButtonStyleForPath" TargetType="{x:Type Button ...

  7. 配置NAT回流导致外网解析到了内网IP

    单位有3个域名,用量很大,2014年开始本人研究部署了Bind+DLZ +Mysql的三机智能多链路DNS,非常好用,优点是: 1.使用Mysql管理记录,配置.管理.查询方便. 2.自动判断运营商, ...

  8. IOS Application Security Testing Cheat Sheet

    IOS Application Security Testing Cheat Sheet    [hide]  1 DRAFT CHEAT SHEET - WORK IN PROGRESS 2 Int ...

  9. Git 执行 「fork 出来的仓库」和「最新版本的原仓库」内容同步更新

    当我们在 GitHub 上 fork 出一个仓库后,如果原仓库更新了,此时怎样才能保证我们 fork 出来的仓库和原仓库内容一致呢?我们一般关注的是仓库的 master(主干分支)的内容,通过以下步骤 ...

  10. 跟随标准与Webkit源码探究DOM -- 获取元素之getElementsByName

    按照name属性获取多元素 -- getElementsByName 标准 DOM 1 定义在HTMLDocument Interface 中,原型NodeList getElementsByName ...