多线程 消费者与生产者 的问题 (线程同步)

问题 :

生产者 需要生产 6个产品后, 消费者 才能消费,  当消费 者 消费 一个后 生产者 继续生产.

同时进行


面向 对象:

生产者  消费者  产品  共享资源  


消费者

public class Consumer implements Runnable {

Util util;


public Consumer(Util util) {

this.util=util;

new Thread(this).start();

}


public void run() {

while(true)

{

util.get();

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

 

}

生产者 

public class Producer implements Runnable {

Util util;


// 生产者

public Producer(Util util) {

this.util = util;

new Thread(this).start();

}


public void run() {

int i = 0;

while (true) {

Motorcycle p = new Motorcycle("川崎", i++);

util.put(p);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}


}


生产的 产品

public class Motorcycle {

private String name;// 产品名称

int id;// 产品编号


public Motorcycle(String name, int id) {

this.name = name;

this.id = id;

}

共享资源 类


public class Util {

private Motorcycle[] boxs = new Motorcycle[5];

private int index = -1;


/*

* 放产品到盒子

*

*/

public synchronized void put(Motorcycle m) {

// if (index == boxs.length - 1) {

if (boxs[4] != null) {

System.out.println("生产者休息");

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

boxs[++index] = m;

System.out.println("生产者:" + m);

notify();

}


/*

* 盒子取产品

*/

public synchronized Motorcycle get() {

//if (index == -1)// 盒子为空

if(boxs[0] ==null)

{

System.out.println("消费者休息");

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

Motorcycle m = boxs[index--];

System.out.println("消费者:" + m);

notify();

return m;

}

}


Test 类

public class Test {

public static void main(String[] args) {

Util u = new Util();

new Producer(u);

new Consumer(u);

}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茅十八呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值