介绍

与synchronized类似,Lock中的为 await() , signal , signalAll()。await()将线程添加到对应的条件队列,signal是将对应的条件队列中等待时间最长的节点放入等待队列中,signalAll()是将条件队列中的所有节点放入等待队列中
image.png

使用

来简单使用下,实现一个阻塞队列

  1. class BoundedBlockingQueue {
  2. private final Lock lock = new ReentrantLock();
  3. private final Condition empty = lock.newCondition();
  4. private final Condition full = lock.newCondition();
  5. private final int CAPACITY;
  6. private Queue<Integer> q = new LinkedList<>();
  7. public BoundedBlockingQueue(int capacity) {
  8. this.CAPACITY = capacity;
  9. }
  10. public void enqueue(int element) throws InterruptedException {
  11. lock.lock();
  12. try{
  13. while(q.size() == CAPACITY){
  14. full.await();
  15. }
  16. q.offer(element);
  17. empty.signalAll();
  18. }finally {
  19. lock.unlock();
  20. }
  21. }
  22. public int dequeue() throws InterruptedException {
  23. lock.lock();
  24. try{
  25. while(q.isEmpty()){
  26. empty.await();
  27. }
  28. int res = q.poll();
  29. full.signalAll();
  30. return res;
  31. }finally {
  32. lock.unlock();
  33. }
  34. }
  35. public int size() {
  36. lock.lock();
  37. try{
  38. return q.size();
  39. }finally {
  40. lock.unlock();
  41. }
  42. }
  43. }