package com.itheima;
//定义一个商品类
class Goods2
{
String name;
String use;
//定义一个标识符,用来判断商品是否已经生产
boolean flag = false;
}
//定义生产者类,用来生产商品
class Producer2 implements Runnable
{
Goods2 good;
Producer2(Goods2 good)
{
this.good = good;
}
@Override
public void run()
{
boolean flag = true;
while(true)
{
synchronized(Goods2.class)
{
//如果商品已经生产,就让生产者等待
if(good.flag)
try
{
Goods2.class.wait();
} catch (InterruptedException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if(flag)
{
//生产者生产一个篮球
good.name = "basketball";
good.use = "play";
flag = false;
}
else
{
//生产者生产一个面包
good.name = "面包";
good.use = "吃的";
flag = true;
}
//商品被生产后,修改标识符,并唤醒消费者
good.flag = true;
Goods2.class.notifyAll();
}
}
}
}
//定义消费者类,用来消费商品
class Consumer2 implements Runnable
{
Goods2 good;
Consumer2(Goods2 good)
{
this.good = good;
}
@Override
public void run()
{
while(true)
{
synchronized(Goods2.class)
{
//如果没有商品,消费者就等待
if(!good.flag)
try
{
Goods2.class.wait();
} catch (InterruptedException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//消费者消费商品
System.out.println(good.name + "---" + good.use);
//消费商品后,修改标识符,并唤醒生产者
good.flag = false;
Goods2.class.notifyAll();
}
}
}
}
public class Test029
{
/**
* @param args
*/
public static void main(String[] args)
{
Goods2 good = new Goods2();
Producer2 producer = new Producer2(good);
Consumer2 consumer = new Consumer2(good);
new Thread(producer).start();
new Thread(consumer).start();
}
} |
|