生产者和消费者的两种方式

在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作。比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界资源(即队列)的占用权。因为生产者如果不释放对临界资源的占用权,那么消费者就无法消费队列中的商品,就不会让队列有空间,那么生产者就会一直无限等待下去。因此,一般情况下,当队列满时,会让生产者交出对临界资源的占用权,并进入挂起状态。然后等待消费者消费了商品,然后消费者通知生产者队列有空间了。同样地,当队列空时,消费者也必须等待,等待生产者通知它队列中有商品了。这种互相通信的过程就是线程间的协作。

  今天我们就来探讨一下Java中线程协作的最常见的两种方式:利用Object.wait()、Object.notify()和使用Condition

  以下是本文目录大纲:

  一.wait()、notify()和notifyAll()

  二.Condition

  三.生产者-消费者模型的实现


一.wait()、notify()和notifyAll()

wait()、notify()和notifyAll()是 Object类 中的方法:

 从这三个方法的文字描述可以知道以下几点信息:

  1)wait()、notify()和notifyAll()方法是本地方法,并且为final方法,无法被重写。

  2)调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)

  3)调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程;

  4)调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程;

  有朋友可能会有疑问:为何这三个不是Thread类声明中的方法,而是Object类中声明的方法(当然由于Thread类继承了Object类,所以Thread也可以调用者三个方法)?其实这个问题很简单,由于每个对象都拥有monitor(即锁),所以让当前线程等待某个对象的锁,当然应该通过这个对象来操作了。而不是用当前线程来操作,因为当前线程可能会等待多个线程的锁,如果通过线程来操作,就非常复杂了。

  上面已经提到,如果调用某个对象的wait()方法,当前线程必须拥有这个对象的monitor(即锁),因此调用wait()方法必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)。

  调用某个对象的wait()方法,相当于让当前线程交出此对象的monitor,然后进入等待状态,等待后续再次获得此对象的锁(Thread类中的sleep方法使当前线程暂停执行一段时间,从而让其他线程有机会继续执行,但它并不释放对象锁);

  notify()方法能够唤醒一个正在等待该对象的monitor的线程,当有多个线程都在等待该对象的monitor的话,则只能唤醒其中一个线程,具体唤醒哪个线程则不得而知。

  同样地,调用某个对象的notify()方法,当前线程也必须拥有这个对象的monitor,因此调用notify()方法必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)。

  nofityAll()方法能够唤醒所有正在等待该对象的monitor的线程,这一点与notify()方法是不同的。

  这里要注意一点:notify()和notifyAll()方法只是唤醒等待该对象的monitor的线程,并不决定哪个线程能够获取到monitor。

  举个简单的例子:假如有三个线程Thread1、Thread2和Thread3都在等待对象objectA的monitor,此时Thread4拥有对象objectA的monitor,当在Thread4中调用objectA.notify()方法之后,Thread1、Thread2和Thread3只有一个能被唤醒。注意,被唤醒不等于立刻就获取了objectA的monitor。假若在Thread4中调用objectA.notifyAll()方法,则Thread1、Thread2和Thread3三个线程都会被唤醒,至于哪个线程接下来能够获取到objectA的monitor就具体依赖于操作系统的调度了。

  上面尤其要注意一点,一个线程被唤醒不代表立即获取了对象的monitor,只有等调用完notify()或者notifyAll()并退出synchronized块,释放对象锁后,其余线程才可获得锁执行。

下面看一个例子就明白了:

public class Test {
    public static Object object = new Object();
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
         
        thread1.start();
         
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         
        thread2.start();
    }
     
    static class Thread1 extends Thread{
        @Override
        public void run() {
            synchronized (object) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                }
                System.out.println("线程"+Thread.currentThread().getName()+"获取到了锁");
            }
        }
    }
     
    static class Thread2 extends Thread{
        @Override
        public void run() {
            synchronized (object) {
                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是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition1的await()、signal()这种方式实现线程间协作更加安全和高效。因此通常来说比较推荐使用Condition,在阻塞队列那一篇博文中就讲述到了,阻塞队列实际上是使用了Condition来模拟线程间协作。

  • Condition是个接口,基本的方法就是await()和signal()方法;
  • Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition() 
  •  调用Condition的await()和signal()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用

  Conditon中的await()对应Object的wait();

  Condition中的signal()对应Object的notify();

  Condition中的signalAll()对应Object的notifyAll()。

三.生产者-消费者模型的实现

package com.norelax.www;

import java.util.PriorityQueue;

/**使用wait和notify实现生产者和消费者模式
 * @author wusong
 *
 */
public class BlockingQueuesDemo {
	//定义一个队列,初始化容量为10
	private PriorityQueue<Integer> queue= new PriorityQueue<Integer>(10);
	

	public static void main(String[] args) {
		BlockingQueuesDemo blockingQueues = new BlockingQueuesDemo();
		Producer producer = blockingQueues.new Producer();
		Customer customer = blockingQueues.new Customer();
		producer.start();
		customer.start();
	}
	
	//生产者
	class Producer extends Thread{

		@Override
		public void run() {
			while (true) {
				synchronized (queue) {
					//判断队列中元素为10,需要等待
					if (queue.size()==10) {
						//阻塞,等待
						try {
							System.out.println("队列已满,等待中...");
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
							queue.notify();
						}
					}
					//放数据
					queue.offer(1);
					queue.notify();
					System.out.println("生产者生产数据,队列中还剩下元素空间为:"+(10-queue.size()));
				}
			}
		}
		
	}
	
	//消费者
	class Customer extends Thread{
		@Override
		public void run() {
			while (true) {
				synchronized (queue) {
					//如果队列中的元素为空,则等待
					if (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());
				}
			}
		}
	}

}
 2.使用Condition实现
package com.norelax.www;

import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**使用wait和notify实现生产者和消费者模式
 * @author wusong
 *
 */
public class BlockingQueuesDemo1 {
	//定义一个队列,初始化容量为10
	private PriorityQueue<Integer> queue= new PriorityQueue<Integer>(10);
	//获取锁
	Lock lock=new ReentrantLock();
	//获取condition
	Condition notFull=lock.newCondition();//生产者
	Condition notEmpty=lock.newCondition();//消费者
	public static void main(String[] args) {
		BlockingQueuesDemo1 blockingQueues = new BlockingQueuesDemo1();
		Producer producer = blockingQueues.new Producer();
		Customer customer = blockingQueues.new Customer();
		producer.start();
		customer.start();
	}
	
	//生产者
	class Producer extends Thread{

		@Override
		public void run() {
			while (true) {
				lock.lock();
				try {
					//判断队列中元素为10,需要等待
					while (queue.size()==10) {
						//阻塞,等待
						try {
							System.out.println("队列已满,等待中...");
							notEmpty.signal();
							notFull.await();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
						//放数据
						queue.offer(1);
						System.out.println("生产者生产数据,队列中还剩下元素空间为:"+(10-queue.size()));
				}finally{
					lock.unlock();
				}
					}
		}
	}
	
	//消费者
	class Customer extends Thread{
		@Override
		public void run() {
			while (true) {
				lock.lock();
				try {
					//如果队列中的元素为空,则等待
					while (queue.size()==0) {
						try {
							System.out.println("对列为空,等待中...");
							notFull.signal();
							notEmpty.await();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
						//消费者取数据
						queue.poll();
						System.out.println("消费者消费数据,队列中元素个数为:"+queue.size());
				
				}finally{
					lock.unlock();
					}
			}
		}
	}
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值