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

2021-05-16 03:29

阅读:613

标签: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


评论


亲,登录后才可以留言!