转自:线程间协作的两种方式:wait、notify、notifyAll和Condition
wait()、notify()和notifyAll()
wait()、notify()和notifyAll()是Object类中的方法:
/**
* Wakes up a single thread that is waiting on this object's
* monitor. If any threads are waiting on this object, one of them
* is chosen to be awakened. The choice is arbitrary and occurs at
* the discretion of the implementation. A thread waits on an object's
* monitor by calling one of the wait methods
*/
public final native void notify();
/**
* Wakes up all threads that are waiting on this object's monitor. A
* thread waits on an object's monitor by calling one of the
* wait methods.
*/
public final native void notifyAll();
/**
* Causes the current thread to wait until either another thread invokes the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object, or a
* specified amount of time has elapsed.
* <p>
* The current thread must own this object's monitor.
*/
public final native void wait(long timeout) throws InterruptedException;
从上面的三个方法中,可以获取到如下信息:
- wait()、notify()和notifyAll()方法都是本地方法,并且为final类型,无法被重写。
- 调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)。
- 调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程。
- 调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程。
注意事项:
- 以上三种方法都必须在同步方法或者同步方法块中进行。
- Thread.sleep()方法只是让当前线程暂停执行一段时间,从而让其他线程有机会继续执行,但它并不释放对象锁。
- wait()方法是相当于当前线程交出此对象的monitor,然后进入等待状态,然后后续再次获得此对象的锁。
- notify()和notifyAll()方法是去唤醒等待该对象的线程,去获取对象的monitor。
- 尤为注意的一点是,一个线程被唤醒不代表立即获取了对象的monitor,只有等调用完了notify或者notifyAll()并退出同步代码块,释放对象锁后,其余线程才可获得执行。
public class ThreadTest {
public static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
//确保线程1先开始运行
Thread.sleep(1000);
t2.start();
}
static class Thread1 extends Thread{
@Override
public void run() {
synchronized (object){
try {
//交出对象的monitor,进入等待状态
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + "获取到了锁");
}
}
}
static class Thread2 extends Thread{
@Override
public void run() {
synchronized (object){
//唤醒线程去获取对象的monitor,但这时候并没有获取到锁
object.notify();
System.out.println("线程" + Thread.currentThread().getName() + "调用了object.notify()方法");
System.out.println("线程" + Thread.currentThread().getName() + "释放了锁");
}
}
}
}
输出结果:
线程Thread-1调用了object.notify()方法
线程Thread-1释放了锁
线程Thread-0获取到了锁
Condition
- Condition是个接口,基本的方法是await()和signal()方法;
- Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition();
- 调用Condition的await()和signal()方法,都必须在lock保护之内,也就是说必须在lock.lock()和lock.unlock()之间才可以使用;
- Condition中的await、signal和signalAll方法与Object中的wait、notify和notifyAll是一一对应的。
使用Condition实现生产者-消费者模型:
public class ConditionDemo {
private int queueSize = 10;
private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
public static void main(String[] args) {
ConditionDemo demo = new ConditionDemo();
ConditionDemo.Consumer consumer = demo.new Consumer();
ConditionDemo.Producer producer = demo.new Producer();
consumer.start();
producer.start();
}
class Consumer extends Thread {
@Override
public void run() {
consume();
}
private void consume() {
while (true) {
lock.lock();
try {
while (queue.size() == 0) {
try {
System.out.println("队列为空,等待数据");
//阻塞消费者
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
//唤醒一个生产者
notFull.signal();
System.out.println("从队列中取走一个元素,队列剩余" + queue.size() + "个元素");
} finally {
lock.unlock();
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
produce();
}
private void produce() {
while (true) {
lock.lock();
try {
while (queue.size() == queueSize) {
try {
System.out.println("队列已满,等待剩余空间");
//阻塞生产者
notFull.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(1);
//唤醒一个消费者
notEmpty.signal();
System.out.println("向队列中插入一个元素,队列剩余空间:" + (queueSize - queue.size()));
} finally {
lock.unlock();
}
}
}
}
}
使用wait()和notify()来实现生产者-消费者模型:
public class ObjectDemo {
private int queueSize = 10;
private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);
public static void main(String[] args){
ObjectDemo demo = new ObjectDemo();
ObjectDemo.Consumer consumer = demo.new Consumer();
ObjectDemo.Producer producer = demo.new Producer();
consumer.start();
producer.start();
}
class Consumer extends Thread{
@Override
public void run() {
consume();
}
private void consume(){
while (true){
synchronized (queue){
while (queue.size() == 0){
try {
System.out.println("队列为空,等待数据");
queue.wait();
} catch (InterruptedException e) {
//注意此处当线程中断时,唤醒另一个线程
e.printStackTrace();
queue.notify();
}
}
queue.poll();
queue.notify();
System.out.println("从队列中取出一个元素,队列中还剩余" + queue.size() + "个元素");
}
}
}
}
class Producer extends Thread{
@Override
public void run() {
produce();
}
private void produce() {
while (true){
synchronized (queue){
while (queue.size() == queueSize){
try {
System.out.println("队列已经满,等待剩余空间");
queue.wait();
}catch (InterruptedException e){
e.printStackTrace();
queue.notify();
}
}
queue.offer(1);
queue.notify();
System.out.println("向队列中插入一个元素,队列剩余空间:" + (queueSize - queue.size()));
}
}
}
}
}
网友评论