Class message{
Private String title;
Private String content;
Private Boolean flag = true;
//flag = = true: It means it can be produced, but not taken.
//flag = = flase: It means it can be taken away, but not produced .
Public synchronized void Set (stringtitle,string content) {
if (This.flag = = False) {
try {
Super.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
This.title = title;
try {
Thread.Sleep (100);
} catch (Interruptedexceptione) {
E.printstacktrace ();
}
this.content = content;
This.flag = false;
Super.notify ();
}
Public synchronized void get () {
if (This.flag = = True) {
try {
Super.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
try {
Thread.Sleep (100);
} catch (Interruptedexceptione) {
E.printstacktrace ();
}
System.out.println (this.title+ "--->" +this.content);
This.flag = true;
Super.notify ();
}
}
Class Productorimplements runnable{
Private Message msg = null;
Public Productor (Message msg) {
this.msg = msg;
}
@Override
public void Run () {
for (int i = 0;i < 50;i++) {
if (i% 2 = = 0) {
this.msg.set ("2012-12-21", " the end of the World ");
}
else{
this.msg.set (" Chische ", "cleaning up and meeting the Doom ");
}
}
}
}
Class Customerimplements runnable{
Private Message msg = null;
Public Customer (Message msg) {
this.msg = msg;
}
@Override
public void Run () {
for (int i = 0;i < 50;i++) {
This.msg.get ();
}
}
}
Public classtestdemo3{
public static void Main (string[] args) {
Message msg = new Message ();
New Thread (Newproductor (msg)). Start ();
New Thread (Newcustomer (msg)). Start ();
}
}
· Wait: publicfinal void Wait () throws Interruptedexception ;
· wake the first waiting thread: Public final void notify () ;
· Wake all Waiting Threads: Public final void Notifyall () .
Multi-thread solution for repetitive set-up and repeat removal of data