若要保证后台线程在trylock()之前运行得到锁,可加“屏障”,如下1,2,3步,而trylock()不管设定时间与否都不会阻塞主线程而是立即返回:

//: concurrency/AttemptLocking.java
// Locks in the concurrent library allow you
// to give up on trying to acquire a lock.
package concurrency; import java.util.concurrent.*;
import java.util.concurrent.locks.*; public class AttemptLocking {
private ReentrantLock lock = new ReentrantLock();
public void untimed() {
boolean captured = lock.tryLock();
try {
// for(int i = 0; i < 10; i++) System.out.println("untime i: " + i);
System.out.println("tryLock(): " + captured);
} finally {
if(captured)
lock.unlock();
}
}
public void timed() {
boolean captured = false;
try {
captured = lock.tryLock(2, TimeUnit.SECONDS);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
try {
// for(int i = 0; i < 10; i++) System.out.println("time i: " + i);
System.out.println("tryLock(2, TimeUnit.SECONDS): " +
captured);
} finally {
if(captured)
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final AttemptLocking al = new AttemptLocking();
al.untimed(); // True -- lock is available
al.timed(); // True -- lock is available
// Now create a separate task to grab the lock:
final CountDownLatch latch = new CountDownLatch(1);//1.增加一个"屏障"
new Thread() {
{
setDaemon(false);
} public void run() {
al.lock.lock();
System.out.println("acquired");
latch.countDown();//2.屏障解除
}
}.start();
Thread.yield(); // Give the 2nd task a chance
latch.await();//3.阻塞在屏障处直到屏障解除
al.untimed(); // False -- lock grabbed by task
al.timed(); // False -- lock grabbed by task
}
} /* Output:
tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
acquired
tryLock(): false
tryLock(2, TimeUnit.SECONDS): false
*///:~

最新文章

  1. Ubuntu搭建NFS
  2. SqlSever基础 datediff 计算两个时间相差多少年份
  3. mongo二维数组操作
  4. MVC为模型增加正则表达式
  5. 基于HTML5的SLG游戏开发( 三):认识PureMVC
  6. ubuntu下为opera26.0安装flash
  7. [Jquery] 操作html 不常用元素方法大全
  8. freemarker 遍历 hashmap 到select option
  9. iOS开发tableview二级联动的细节实现中注意的细节总结
  10. python,Day1,基础1
  11. C#演示如何使用 XML 将源码编入文档
  12. 将golang中变量重置为零的reflect方法
  13. Manacher&#39;s Algorithm &amp;&amp; 647. Palindromic Substrings 计算回文子串的算法
  14. Django项目的创建及基本使用
  15. [Web 前端] qs.parse()、qs.stringify()使用方法
  16. Oracle——存储过程简单入门实例
  17. awk数组
  18. opencv 学习笔记
  19. Fragment的setUserVisibleHint方法实现懒加载,但setUserVisibleHint 不起作用?
  20. 《Java Concurrency》读书笔记,构建线程安全应用程序

热门文章

  1. u3d demo起步第二章
  2. UI组件之AdapterView及其子类关系,Adapter接口及事实上现类关系
  3. HDU 1287 破译密码 异或运算
  4. POJ 1511 Invitation Cards (ZOJ 2008) 使用优先队列的dijkstra
  5. 6 、字符编码笔记:ASCII,Unicode和UTF-8
  6. 【Codeforces Round #185 (Div. 2) A】 Whose sentence is it?
  7. Java 线程第三版 第九章 Thread调度 读书笔记
  8. android.app.Dialog(23)里window的那些事(坑)
  9. 【Lucene4.8教程之三】搜索 2014-06-21 09:53 1532人阅读 评论(0) 收藏
  10. JS和PHP和JAVA的正则表达式的区别(java没有分解符,java中的转义字符是\\)