java并发系列之wait与notify的理解与实例

 生产者、消费者模型

package thread;

/**
 * 生产者、消费者模型
 *
 */
public class WaitNotifyDemo {
	//计数池子
	private int count=0;
	//池子最大容量
	private static final int MAX=50;
	//池子最小容量
	private static final int MIN=0;
	
	
	public void product(){
		//wait和notify一定要结合synchronized用
		synchronized (this) {
			//while if的区别:
			//假如是while,这个生产者拿到了锁,但池子满了,就会阻塞,释放锁。等它再次拿到锁,继续执行下面的代码,如果是while,就会又判断一次池子是否满了,
			//所以这个生产者无论阻塞多少次,都要生产一次,但是if不会
			while(count>=MAX){
				System.out.println("当前数量:"+count+",生产者阻塞!");
				try {
					//当线程执行wait()方法时候,会释放当前的锁,然后让出CPU,进入等待状态
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("当前数量:"+count+",生产者生产!");
			count++;
			
			//唤醒其他线程,但不会释放锁,只有wait方法或者synchronized同步代码块执行完才会释放锁,所以一般notify写在最后面,notifyAll会唤醒多个线程
			this.notify();
		}
	}
	
	public void consumer(){
		
		synchronized (this) {
			while(count<=MIN){
				System.err.println("当前数量:"+count+",消费者阻塞!");
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.err.println("当前数量:"+count+",消费者消费!");
			count--;
			this.notify();
		}
		
	}
	
	
	public static void main(String[] args) {
		
		final WaitNotifyDemo waitNotifyDemo = new WaitNotifyDemo();
		
		
		//开启两个线程,一个不停的产生生产者线程,一个不停的产生消费者线程
		//时间可以控制,比如下面,每1秒来一个生产者,每3秒来一个消费者,也就是生产速度>消费速度,池子会在一定时间后满了
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					
					new Thread(new Runnable() {
						@Override
						public void run() {
							waitNotifyDemo.product();
						}
					}).start();
					
					
					//每3秒产生一个生产者
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					
					new Thread(new Runnable() {
						@Override
						public void run() {
							waitNotifyDemo.consumer();
						}
					}).start();
					
					
					//每1秒产生一个消费者
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		
	}
		
		
}
发布了89 篇原创文章 · 获赞 67 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/xl_1803/article/details/99979887