多线程----简单的生产者和消费者
2021-05-16 03:29
标签:inter 图片 时代 while alt rri 生产者 imp this package cn.zz; //简单的生产者和消费者 public synchronized void Set(String name) { public synchronized void out() { class Producer implements Runnable { public Producer(Resource res) { @Override } class Consumer implements Runnable { public Consumer(Resource res) { @Override } } public class ProducerAndConsumer { } 图上为运行时代码 ,简单的一对一关系,一个生产者,一个消费者,交替运行。 多线程----简单的生产者和消费者 标签:inter 图片 时代 while alt rri 生产者 imp this 原文地址:https://www.cnblogs.com/twqwe/p/9749902.html
class Resource {
private String name;
private int count;
private boolean flag = false;
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();
}
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();
}
}
private Resource res;
this.res = res;
}
public void run() {
while (true) {
res.Set("++商品--");
}
}
private Resource res;
this.res = res;
}
public void run() {
while (true) {
res.out();
}
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();
}
上一篇:Java常见框架和工具