67,513
社区成员
发帖
与我相关
我的任务
分享
public class WaitNotifyDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MessageBoard m = new MessageBoard();//构造共享的信息板类对象
Reader readfrom_m = new Reader(m);
Writer writeto_m = new Writer(m);
readfrom_m.start();
writeto_m.start();
}
}
class MessageBoard { //共享的信息板
private String message;
private boolean ready = false;
public synchronized String read(){ //ERROR
while(ready == false){
try{
wait();
}catch(InterruptedException e){}
ready = false;
notify();
return message;
}
}
public synchronized void write(String s) {
while(ready == true){
try{
wait();
}catch(InterruptedException e){}
message = s;
ready = true;
notify();
}
}
}
class Reader extends Thread{ //定义读线程类
private MessageBoard mBoard;
public Reader(MessageBoard m){
mBoard = m;
}
public void run(){
String s = "";
boolean reading = true;
while(reading){
s = mBoard.read();
System.out.println("Reader read:"+s);
if(s.equals("logoff"))
reading = false;
}
System.out.println("Finished: 10 seconds...");
try{
sleep(10000);
}catch(InterruptedException e){}
}
}
class Writer extends Thread{ // 定义写线程类
private MessageBoard mBoard;
private String messages[] = {
"Monday :--------","....","Sunday : --------"
};
public Writer(MessageBoard m){
mBoard = m;
}
public void run(){
for(int i=0;i<messages.length;i++){
mBoard.write(messages[i]);
System.out.println("Writer wrote:"+messages[i]);
try{
sleep((int)(Math.random()*100));
}catch(InterruptedException e){}
}
mBoard.write("logoff");
}
}