java多线程生产者与消费者问题_java多线程实现生产者与消费者问题

生产者与消费者多线程实现,首先的问题就是同步,就是关于临界资源的访问

我们首先来定义一个临界资源类,这里设为Q

class Q

{ int z=4;

}

这个int型的z就是我假设的临界资源的个数

然后是生产者的put动作

synchronized void put()

{

if(z>0)//当临界资源的个数大于0时,生产者等待wait,否则,生产者进行生产,生产之后唤醒notifyAll()挂起的消费者

{

try{wait();}catch(Exception e){}

}

else

{

System.out.print(Thread.currentThread()+"   ");

System.out.println(++z);

try{notifyAll();}catch(Exception e){}

}

}

然后是消费者进行消费的过程get

synchronized void get()

{

if(z<=0)//当临界资源的个数等于或者小于0时,消费者进程等待

{

try{wait();}catch(Exception e){}

}

else

{

System.out.print(Thread.currentThread().getName()+"   ");

System.out.println(z--);

if(z==0)//当一个消费者消费完之后检查了一下临界资源,发现资源为0,那么唤醒生产者来进行生产

{

notify();

}

}

}

然后是生产者和消费者类的定义

这里的生产者和消费者都是Thread类的子类,故都要完成run方法,这里run方法一般为无限循环

class producer extends Thread

{

Q q;

public producer(Q q)

{

this.q=q;

}

public void run()

{

while(true)

{

q.put();

}

}

}

class consumer extends Thread

{

Q q;

public  consumer(Q q)

{

this.q=q;

}

public void run()

{

while(true)

{

q.get();

}

}

}

这里需要注意,因为只能生产一个临界资源对象,这里我们放在主函数里面,所以,需要构造生产者和消费者的构造函数,并将临界资源作为参数传递进来,进行put与get操作

整个函数定义如下:

public class a

{

public static void main(String[]args)

{    Q q=new Q();

Thread t1,t2,t3;

t1=new producer(q);

t2=new consumer(q);

t3=new consumer(q);

t1.start();

t2.start();

t3.start();

}

}

class Q

{

int z=4;

synchronized void put()

{

if(z>0)

{

try{wait();}catch(Exception e){}

}

else

{

System.out.print(Thread.currentThread()+"   ");

System.out.println(++z);

try{notifyAll();}catch(Exception e){}

}

}

synchronized void get()

{

if(z<=0)

{

try{wait();}catch(Exception e){}

}

else

{

System.out.print(Thread.currentThread().getName()+"   ");

System.out.println(z--);

if(z==0)

{

notify();

}

}

}

}

class producer extends Thread

{

Q q;

public producer(Q q)

{

this.q=q;

}

public void run()

{

while(true)

{

q.put();

}

}

}

class consumer extends Thread

{

Q q;

public  consumer(Q q)

{

this.q=q;

}

public void run()

{

while(true)

{

q.get();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值