码迷,mamicode.com
首页 > 编程语言 > 详细

多线程----简单的生产者和消费者

时间:2018-10-07 13:53:43      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:inter   图片   时代   while   alt   rri   生产者   imp   this   

package cn.zz;

//简单的生产者和消费者
class Resource {
private String name;
private int count;
private boolean flag = false;

public synchronized void Set(String name) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name + "..." + count++;
System.out.println(Thread.currentThread().getName() + "...生产者"
+ this.name);
flag = true;
this.notify();
}

public synchronized void out() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "...消费者....."
+ this.name);
flag = false;
this.notify();
}
}

class Producer implements Runnable {
private Resource res;

public Producer(Resource res) {
this.res = res;
}

@Override
public void run() {
while (true) {
res.Set("++商品--");
}
}

}

class Consumer implements Runnable {
private Resource res;

public Consumer(Resource res) {
this.res = res;
}

@Override
public void run() {
while (true) {
res.out();
}

}

}

public class ProducerAndConsumer {
public static void main(String[] args) {
Resource res = new Resource();
Consumer con = new Consumer(res);
Producer pro = new Producer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}

}

 

 

 

技术分享图片

图上为运行时代码 ,简单的一对一关系,一个生产者,一个消费者,交替运行。

多线程----简单的生产者和消费者

标签:inter   图片   时代   while   alt   rri   生产者   imp   this   

原文地址:https://www.cnblogs.com/twqwe/p/9749902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!