package com.itheima;
//定义一个商品类
class Goods1
{
String name;
String use;
}
//定义生产者类,用来生产商品
class Producer1 implements Runnable
{
Goods1 good;
Producer1(Goods1 good)
{
this.good = good;
}
@Override
public void run()
{
boolean flag = true;
while(true)
{
synchronized(Goods1.class)
{
if(flag)
{
//生产者生产一个篮球
good.name = "basketball";
good.use = "play";
flag = false;
}
else
{
//生产者生产一个面包
good.name = "面包";
good.use = "吃的";
flag = true;
}
}
}
}
}
//定义消费者类,用来消费商品
class Consumer1 implements Runnable
{
Goods1 good;
Consumer1(Goods1 good)
{
this.good = good;
}
@Override
public void run()
{
while(true)
{
synchronized(Goods1.class)
{
//消费者消费商品
System.out.println(good.name + "---" + good.use);
}
}
}
}
public class Test028
{
/**
* @param args
*/
public static void main(String[] args)
{
Goods1 good = new Goods1();
Producer1 producer = new Producer1(good);
Consumer1 consumer = new Consumer1(good);
new Thread(producer).start();
new Thread(consumer).start();
}
}
|
|