文章目录
Java中的锁(三)使用ConditionCondition中的方法注意事项实现等待通知机制
Java中的锁(三)
使用Condition
Condition和Lock结合使用 = wait/notify和synchronized结合使用
Condition中的方法
void await() = waitvoid await(long nanos) 有超时时间 = wait(long timeout)void signal = notify 唤醒一个void signalAll() = notifyAll 唤醒所有
注意事项
和wait、notify一样,在执行await、signal、signalAll的前提也必须获得lock锁才可以执行
实现等待通知机制
import java
.util
.concurrent
.TimeUnit
;
import java
.util
.concurrent
.locks
.Condition
;
import java
.util
.concurrent
.locks
.Lock
;
import java
.util
.concurrent
.locks
.ReentrantLock
;
import lombok
.SneakyThrows
;
import org
.junit
.Test
;
public final class ThreadLockConditionTest {
static Lock lock
= new ReentrantLock();
static Condition condition
= lock
.newCondition();
static boolean flag
= true;
@Test
@SneakyThrows
public void assertLockCondition() {
Thread threadN
= new Thread(new ThreadLockConditionTest.threadN(), "threadN");
Thread threadM
= new Thread(new ThreadLockConditionTest.threadM(), "threadM");
threadN
.start();
TimeUnit
.SECONDS
.sleep(1);
threadM
.start();
TimeUnit
.SECONDS
.sleep(10);
}
static class threadN implements Runnable {
@Override
public void run() {
lock
.lock();
while (flag
) {
System
.out
.println(Thread
.currentThread().getName() + " flag is true wait");
try {
condition
.await();
} catch (InterruptedException exception
) {
exception
.printStackTrace();
} finally {
lock
.unlock();
}
System
.out
.println(Thread
.currentThread().getName() + "falg is false running");
}
}
}
static class threadM implements Runnable {
@Override
public void run() {
lock
.lock();
System
.out
.println(Thread
.currentThread().getName() + " acquire lock");
flag
= false;
try {
TimeUnit
.SECONDS
.sleep(3);
condition
.signalAll();
} catch (InterruptedException exception
) {
exception
.printStackTrace();
}finally {
lock
.unlock();
}
lock
.lock();
System
.out
.println(Thread
.currentThread().getName() + " acquire again");
condition
.signalAll();
lock
.unlock();
}
}
}