黑马程序员技术交流社区
标题:
黑马程序员-Java基础-多线程同步安全事例
[打印本页]
作者:
QQheima
时间:
2015-6-14 21:42
标题:
黑马程序员-Java基础-多线程同步安全事例
消费者和生产者的例子
在本例中,有多个生产者和多个消费者。每生产一个商品,就消费一个商品,不能积压商品。
要解决的问题
1、多个生产者生产商品,要同步进行,一个生产者存储商品时,另一个生产者不能同时存储商品。
2、多个消费者消费时。要同步进行,一个消费者取商品时,另一个消费者不能同时取商品。
3、生产者在存储商品时,消费者不能取商品。
4、消费者取商品时,生产者不能存储商品。
以下是实现代码:
public class PorductorAndConsumer {
public static void main(String[] args) {
Source s = new Source();
Productor p = new Productor(s);
Consumer c = new Consumer(s);
//两个生产者
new Thread(p).start();
new Thread(p).start();
//两个消费者
new Thread(c).start();
new Thread(c).start();
}
}
class Source{
String name;
int count = 0;
boolean flag = true;
//存商品
//synchronized:每次只能有一个生产者存商品
public synchronized void input(String name){
//如果有商品,就等待消费者取走商品
while(flag){//***有多个生产者时,就要用while,不能用if。因为如果用if,当被阻塞进程别唤醒时,不会再次去判断生产条件flag。
try {this.wait();} catch (InterruptedException e) {}
}
this.name = name+count++;
System.out.println(Thread.currentThread().getName()+"***iiiii***"+this.name);
//有了产品
flag = true;
//就唤醒消费者
//有多个消费者时,就要用notifyAll(),不能用notify
this.notifyAll();
}
//取商品
//synchronized:每次只能有一个消费者取商品
public synchronized void output(){
//如果没有有商品,就等待生产者存进商品
while(!flag){//***有多个消费者时,就要用while,不能用if。
try {this.wait();} catch (InterruptedException e) {}
}
System.out.println(Thread.currentThread().getName()+"---ooooo---"+this.name);
//没有了产品
flag = false;
//就唤醒生产者
//有多个生产者时,就要用notifyAll(),不能用notify
this.notifyAll();
}
}
class Productor implements Runnable{
Source s;
public Productor(Source s){
this.s = s;
}
public void run(){
//一直生产
while(true){
s.input("Productor");
}
}
}
class Consumer implements Runnable{
Source s;
public Consumer(Source s){
this.s = s;
}
public void run(){
//一直消费
while(true){
s.output();
}
}
}
复制代码
运行结果:
360截图20150614214146897.jpg
(130.01 KB, 下载次数: 28)
下载附件
2015-6-14 21:42 上传
作者:
古风_菜鸟
时间:
2015-6-14 22:30
学习回顾了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2