/**
* @author wenhui
* @description 多线程间通讯
* @Date 2019/11/3
*/
class Source {
public String name;
public int age;
public boolean flag = false;
}
class Producer implements Runnable {
private Source source;
public Producer(Source source) {
this.source = source;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (source) {
if (source.flag) {
try {
source.wait(); // 等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == 0) {
source.name = "name1";
source.age = 23;
} else {
source.name = "name2";
source.age = 25;
}
count = (count+1) % 2;
source.flag = true;
source.notify(); // 唤醒
}
}
}
}
class Comsumer implements Runnable {
private Source source;
public Comsumer(Source source) {
this.source = source;
}
@Override
public void run() {
while (true) {
synchronized (source) {
if (!source.flag) {
try {
source.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("name: "+source.name+" age: "+source.age);
source.flag = false;
source.notify();
}
}
}
}
public class MQTest {
public static void main(String[] args) {
Source source = new Source();
Producer producer = new Producer(source);
Comsumer comsumer = new Comsumer(source);
Thread thread1 = new Thread(producer);
Thread thread2 = new Thread(comsumer);
thread1.start();
thread2.start();
}
}
输出结果: