问题描述:保持多线程同步 生产一个消费一个
class Message{
private String title;
private String content;
private boolean flag=true;
public synchronized void set(String title,String content) {
if(this.flag==false) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title=title;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.content=content;
this.flag=false;
super.notify();
}
public synchronized String get() {
if(flag==true) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}try {
return this.title+"-"+this.content;
}finally {
this.flag=true;
super.notify();
}
}
}
class Producer implements Runnable{
private Message msg;
public Producer(Message msg) {
this.msg=msg;
}@Override
public void run() {
for(int x=0;x<100;x++) {
if(x%2==0) {
this.msg.set("王健","宇宙大帅哥");
}else {
this.msg.set("赵高","第一人");
}
}
}
}
class Consumer implements Runnable{
private Message msg;
public Consumer(Message msg) {
this.msg=msg;
}
@Override
public void run() {
for(int x=0;x<100;x++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.msg.get());
}
}
}
public class Test1 {
public static void main(String[] args) throws Exception {
Message msg=new Message();
**new Thread(new Producer(msg)).start();
new Thread(new Consumer(msg)).start();
}
}