------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
只函数Main
public static void main(String[] args)
{// TODO Auto-generated method stub
ZiYuan zy = new ZiYuan();
Shengchan sc = new Shengchan(zy);
XiaoFei xf = new XiaoFei(zy);
Thread th1 = new Thread(sc);
Thread th2 = new Thread(xf);
Thread th3 = new Thread(sc);
Thread th4 = new Thread(xf);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
共享资源
class ZiYuan
{
private String name ;
private int sex = 1 ;
private boolean flse = false;
//生成方法
public synchronized void Shengchan(String name)
{
while (flse)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name+"......"+sex++ ;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flse = true ;
this.notifyAll();
}
//消费者方法
public synchronized void Xiaofei()
{
while (!flse)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+".....消费者....."+this.name);
flse = false;
this.notifyAll();
}
}
//生产者对象
class Shengchan implements Runnable
{
private ZiYuan zy ;
public Shengchan(ZiYuan zy)
{
this.zy = zy ;
}
@Override
public void run()
{
while (true)
{
zy.Shengchan("烤鸭");
}
}
}
//消费者
class XiaoFei implements Runnable
{
private ZiYuan zy ;
public XiaoFei(ZiYuan zy)
{
this.zy = zy ;
}
@Override
public void run()
{
while (true)
{
zy.Xiaofei();
}
}
}