thread_AtomicBoolean
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的更多相关文章
随机推荐
- ARM中C和汇编混合编程及示例(转)
在嵌入式系统开发中,目前使用的主要编程语言是C和汇编,C++已经有相应的编译器,但是现在使用还是比较少的.在稍大规模的嵌入式软件中,例如含有OS,大部分的代码都是用C编写的,主要是因为C语言的结构比较 ...
- .NET错误The 'targetFramework' attribute in the <compilation> element of the Web.config file is used only to target version 4.0 and later of the .NET Framework
错误描述: The 'targetFramework' attribute in the <compilation> element of the Web.config file is u ...
- Scala 深入浅出实战经典 第58讲:Scala中Abstract Types实战详解
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...
- Codeforces Round #383 (Div. 2) 题解【ABCDE】
Codeforces Round #383 (Div. 2) A. Arpa's hard exam and Mehrdad's naive cheat 题意 求1378^n mod 10 题解 直接 ...
- Apple开发者网站中一些比较有用的文档
支持IPv6 DNS64/NAT64网络 关于plist文件中的键与值 Apple各种审核准则以及设计准则
- jQuery File Upload跨域上传
最近在做一个一手粮互联网项目,方案为前后端分离,自己负责前端框架,采用了Requirejs+avalonjs+jquery三个框架完成. 前后端通过跨域实现接口调用,中间也发现了不少问题,尤其是在富文 ...
- WordPress添加固定位置的百度分享按钮
第一步,在你所用主题目录新建一个名称为:share.php的模板文件,将下面的代码复制到进去并保存 <div id="share"> <div class=&qu ...
- Entity Framework: Joining in memory data with DbSet
转载自:https://ilmatte.wordpress.com/2013/01/06/entity-framework-joining-in-memory-data-with-dbset/ The ...
- Spring4 MVC Hibernate4集成 Annotation
Spring4 MVC Hibernate4集成 Annotation 一.本文所用环境 二.工程目录 三.Maven添加依赖 四.新建数据库表 五.配置文件 六.Model层 七.DAO层 八.Se ...
- Maven3路程(三)用Maven创建第一个web项目(2)servlet演示
上一章用Maven新建了web项目成功后,本文演示在此基础上应用servlet. 1.首先修改pom.xml文件,添加servlet依赖 <project xmlns="http:// ...