private final static Lock lock = new ReentrantLock();
private final static Condition cond = lock.newCondition();
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
lock.lock();//换成读写锁
doSomething();
cond.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
}
如上,当我们调用cond.await();JDK底层调用了LockSupport.park,JVM调用了操作系统posix接口pthread_cond_wait(&cond,mutex)函数。
这个函数将线程加入等待队列中,并让线程睡眠。通过for(::)函数检查&cond是否满足,来唤醒等待队列的线程。
do { \
DEFINE_WAIT(__wait); \
\
for (;;) { \
prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \
if (condition) \
break; \
if (!signal_pending(current)) { \
schedule(); \
continue; \
} \
ret = -ERESTARTSYS; \
break; \
} \
finish_wait(&wq, &__wait); \
} while (0)
如上图,操作系统循环调用条件是否满足函数,判断是否唤醒当前线程。与我的初衷想法是一样的。