多线程----简单的生产者和消费者
Posted twqwe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程----简单的生产者和消费者相关的知识,希望对你有一定的参考价值。
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();
}
}
图上为运行时代码 ,简单的一对一关系,一个生产者,一个消费者,交替运行。
以上是关于多线程----简单的生产者和消费者的主要内容,如果未能解决你的问题,请参考以下文章