notifyAll()会立刻释放锁吗?

不会。需要等到synchronized里面的代码块执行玩才会在释放锁。

案例 : 工厂共需要生产30个产品(产品1~产品30), 生产者每生产5个产品就会通知消费者来消费,等到5件产品消费完了然后再通知生产者继续生产,直到30个产品都被生产和消费后结束。生产一个产生默认需要200ms, 消费一个产品需要100毫秒。

package FactoryAndCustomer;

import java.util.LinkedList;

public class Factory {
	
	private LinkedList<Product> list = new LinkedList<>();

	private Factory() {
		super();
	}
	public static Factory getInstance() {
		return new Factory();
	}
	public synchronized void createBatchProduct() throws InterruptedException {
		for (int i = 0; i <= 30 ; i++) {
			createOne(new Product(i));
		}
	}
	public void createOne(Product product) throws InterruptedException {
		while(list.size() == 5) {
			this.wait();
		}
		list.add(product);
		Thread.sleep(200);
		System.out.println(Thread.currentThread().getName()+"成功生产出"+product);
		this.notifyAll();
	}
	
	public synchronized void  consumeBatchProduct() throws InterruptedException {
		for (int i = 0; i <= 30 ; i++) {
			consumeOne();
		}
		}
	
	public void consumeOne() throws InterruptedException {
		while(list.isEmpty()) {
			this.wait();
		}
		Product product = list.removeLast();
		Thread.sleep(100);
		System.out.println(Thread.currentThread().getName()+"成功消费"+product);
		this.notifyAll(); 
	}
}
package FactoryAndCustomer;

public class Product {
private int id;

public Product(int id) {
	super();
	this.id = id;
}

	@Override
	public String toString() {
		return id + "号产品";
	}

}
package FactoryAndCustomer;

public class Producter extends Thread{
	private Factory factory;
	
	public Producter(String name, Factory factory) {
		super(name);
		this.factory = factory;
	}
	
	@Override
	public void run() {
		try {
			factory.createBatchProduct();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
package FactoryAndCustomer;

public class Customer extends Thread{
	private Factory factory;
	
	public Customer(String name, Factory factory) {
		super(name);
		this.factory = factory;
	}
	@Override
	public void run() {
		try {
			factory.consumeBatchProduct();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
package FactoryAndCustomer;

public class testMain {
public static void main(String[] args) {
	
	Factory factory = Factory.getInstance();
	Producter producter = new Producter("生产者", factory);
	Customer customer = new Customer("消费者", factory);
	
	producter.start();
	customer.start();
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值