• Java编程思想学习笔记-使用显式的Lock对象


    若要保证后台线程在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
    *///:~
  • 相关阅读:
    html之长文本框置顶
    Red Hat Enterprise Linux Server 6.5安装GCC 4.9.2
    精通正则表达式
    解决UNION ALL合并两个结果集后排序的问题
    ELK搭建日志管理系统记录
    Spring Boot使用@ConfigurationProperties 读取自定义的properties的方法
    maven配置profile,按指定环境打包
    java自定义标签,tld文件,获取数据字典的值
    JAVA实现RSA签名、验签
    jquery.validate.js中的remote用法
  • 原文地址:https://www.cnblogs.com/lionfight/p/3171878.html
Copyright © 2020-2023  润新知