java中,wait和notify这两个方法是一对,wait方法阻塞当前线程,而notify是唤醒被wait方法阻塞的线程。
首先,需要说明的是,wait和notify方法都是Object的实例方法,要执行这两个方法,有一个前提就是,当前线程必须获其对象的monitor(俗称“锁”),否则会抛出IllegalMonitorStateException异常,所以这两个方法必须在同步块代码(synchronized)里面调用。
有生产商品和拿取商品两种方法
class ProduceAndConsume {
final int MAX_PRODUCT = 20;
final int MIN_PRODUCT = 0;
int product;
public synchronized void produce()
{
while(true){
System.out.println(product);
if(product >= MAX_PRODUCT)
{
try
{
System.out.println("产品已满,请稍候再生产");
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
product++;
System.out.println("生产者生产第" + product + "个产品.");
notifyAll(); //通知等待区的消费者可以取出产品了
}
}
public synchronized void consume()
{
while (true){
System.out.println(product);
if(product <= MIN_PRODUCT)
{
try
{
System.out.println("缺货,稍候再取");
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("消费者取走了第" + product + "个产品.");
product--;
notifyAll(); //通知等待去的生产者可以生产产品了
}
}
}
Thread2和Thread3
涉及到多线程的方法调用,把ProduceAndConsume类传给他就行,由toString方法可知,引用的是同一变量
继承了Thread类,在run方法中执行生产或者消费方法
class Thread2 extends Thread{
ProduceAndConsume PC;
public Thread2(ProduceAndConsume produceAndConsume){
PC = produceAndConsume;
System.out.println(PC.toString());
}
@Override
public void run() {
PC.consume();
}
}
class Thread3 extends Thread{
ProduceAndConsume PC;
public Thread3(ProduceAndConsume produceAndConsume){
PC = produceAndConsume;
System.out.println(PC.toString());
}
@Override
public void run() {
PC.produce();
}
}
main主方法
2种线程各新建一种,执行就行了
public class Thread1 {
public static void main(String[] args) {
ProduceAndConsume pc = new ProduceAndConsume();
Thread2 thread2 = new Thread2(pc);
Thread3 thread3 = new Thread3(pc);
thread2.start();
thread3.start();
}
}
接下来程序就会无限运行,生产到最大数量就会唤醒消费者线程来消费,消费到最低数量就会唤醒生产者线程来生产
运行截图


