生产者、消费者 各占一个Message对象
import org.omg.PortableServer.THREAD_POLICY_ID;
class Producter implements Runnable{
private Message msg;
public Producter(Message msg) {
this.msg = msg;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i%2==0){
this.msg.set("曹文文","大帅哥");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
this.msg.set("王莽","小帅哥");
}
}
}
}
class Consumer implements Runnable{
private Message msg;
public Consumer(Message msg) {
this.msg = msg;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.msg.get());
}
}
}
class Message{
private String title;
private String content;
public boolean flag=false;//可以生产
public synchronized void set(String title,String content){
if(flag==true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title=title;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.content=content;
flag=true;
super.notify();
}
public synchronized String get(){
if(flag==false){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag=false;
super.notify();
return this.title+"-"+this.content;
}
}
public class Main {
public static void main(String[] args) {
Message msg = new Message();
new Thread(new Producter(msg)).start();
new Thread(new Consumer(msg)).start();
}
}