本文主要是介绍JAVA 生产者消费者模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package thread;
class Message {
private String title;
private String content;
// true:允许生产,但是不允许消费; false:允许消费,不允许生产
private boolean flag = true;
public synchronized void set(String title, String content) {
if (!flag) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title = title;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.content = content;
flag = false; //已经生产过了
super.notify();
}
public synchronized String get() {
if (flag) { //还未生产,需要等待
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
return this.title + " - " + this.content;
} finally {
flag = true; //继续生产
super.notify(); //唤醒等待线程
}
}
}
class Producer implements Runnable {
private Message message;
public Producer(Message message) {
this.message = message;
}
@Override
public void run() {
for (int k = 0; k < 100; k++) {
if (k % 2 == 0) {
this.message.set("Gavin", "云龙第一帅");
} else {
this.message.set("小强", "猥琐第一人");
}
}
}
}
class Comsunmer implements Runnable {
private Message message;
public Comsunmer(Message message) {
this.message = message;
}
@Override
public void run() {
for (int k = 0; k < 100; k++) {
System.out.println(this.message.get());
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Message message = new Message();
new Thread(new Producer(message)).start();
new Thread(new Comsunmer(message)).start();
}
}
这篇关于JAVA 生产者消费者模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!