多线程—生产者于消费者实例

本文介绍了一个典型的生产者消费者模式实现案例,使用Java多线程技术。通过共享资源类`ZiYuan`来协调多个生产者与消费者的同步操作,演示了如何使用`synchronized`关键字和`wait`、`notifyAll`方法确保线程间的正确同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



------- <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();
}
}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值