23. tháng 2 2025
Condition cũng ceo nhà cái là bóng đá ngoại hạng anh trực tiếp hôm nay một phần quan trọng trong AQS. Trước tiên, hãy xem đoạn mu88 mu88 casino mã ví dụ sau đây, đoạn mã này có lẽ đến từ Doug Lea và có thể tìm thấy trong phần javadoc về condition. Thực tế, ông đã từng viết một phiên bản dựa trên synchronized
, mà tôi sẽ chia sẻ ở phần cuối.
1import java.util.concurrent.locks.Condition;
2import java.util.concurrent.locks.Lock;
3import java.util.concurrent.locks.ReentrantLock;
4
5class BoundedBuffer {
6 final Lock lock = new ReentrantLock();
7 final Condition notFull = lock.newCondition();
8 final Condition notEmpty = lock.newCondition();
9
10 final Object[] items = new Object[100];
11 int putptr, takeptr, count;
12
13 public void put(Object x) throws InterruptedException {
14 lock.lock();
15 try {
16 while (count == items.length)
17 notFull.await();
18 items[putptr] = x;
19 if (++putptr == items.length) putptr = 0;
20 ++count;
21 notEmpty.signal();
22 } finally {
23 lock.unlock();
24 }
25 }
26
27 public Object take() throws InterruptedException {
28 lock.lock();
29 try {
30 while (count == 0)
31 notEmpty.await();
32 Object x = items[takeptr];
33 if (++takeptr == items.length) takeptr = 0;
34 --count;
35 notFull.signal();
36 return x;
37 } finally {
38 lock.unlock();
39 }
40 }
41}