有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java所有线程都被锁定了?

获取锁后,线程应该休眠一定时间(本例中为6000ms),以防止另一个线程获取锁。当我使用l1.lock()方法时,它工作正常,但当我使用l1.tryLock()l1.tryLock(1000,TimeUnit.MILLISECOND)时,两个线程都在前一个线程释放锁之前获取锁。怎么可能呢

import java.util.concurrent.locks.*;
import java.util.concurrent.locks.Lock;

class MyLocks implements Runnable {
  static Lock l1;

  public static void main(String... asd) {
    l1 = new ReentrantLock();
    MyLocks obj = new MyLocks();
    new Thread(obj).start();
    new Thread(obj).start();
  }

  public void run() {
    System.out.println(Thread.currentThread().getName() + " is try to acquire lock");
    try {
      l1.trylock();
     // only those thread which has acquired lock will get here. 
      System.out.println(Thread.currentThread().getName() + " has acquired lock");

      Thread.sleep(6000);

    } catch (Exception e) {
    }
    l1.unlock();
  }
}

共 (1) 个答案

  1. # 1 楼答案

    一个常见的错误是调用一个方法并忽略结果。很可能你正在跑步

    lock.tryLock(); // notice this ignores whether the lock was obtained or not.
    

    当你应该做这样的事情的时候

    while(!lock.tryLock(1, TimeUnit.SECOND)) {
      System.out.println(Thread.currentThread().getName()+" - Couldn't get lock, waiting");
    }
    

    注意:不要放弃异常,除非您非常确信它们不重要

    }catch(Exception e){} // something when wrong but lets pretend it didn't
    

    有关如何处理异常的一些提示

    https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html