zoukankan      html  css  js  c++  java
  • 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
    *///:~
  • 相关阅读:
    P1036 选数(python)解题报告
    P1009 阶乘之和(python)解题报告
    P1002 过河卒(python) 解题报告
    来一波数据结构
    KMP算法
    链表实现约瑟夫
    闲谈Tampermonkey
    CF#574E. OpenStreetMap 题解
    洛谷 P2033 Chessboard Dance
    洛谷 P2056 采花
  • 原文地址:https://www.cnblogs.com/lionfight/p/3171878.html
Copyright © 2011-2022 走看看