Я пытаюсь реализовать thread wait() и notify(), но метод уведомления не работает, можете ли вы мне помочь? Я хочу, чтобы читательский поток попытался прочитать из своего сообщения; если ящик сообщений пуст, читатель ждет, пока писатель выполнит задание. Но после действия уведомления читатель все еще ждет и ничего не делает, и писатель продолжает свою работу. это мой код (другие пользовательские объекты отлично работает):java-известить тему из темы
public class TrheadTEST {
private static class AgentThred implements Runnable {
private final String name;
private final String category;
private final PersonalAgentID agentID; // it has name and category
private AgentThred obiettivo;
private Thread trd; // i try to call notify for a specific thread.
public MessageBox msgx; // each thread has a messagebox. Agent can read only her own messagebox
public AgentThred(String nam, String cat){
this.name = nam;
this.category = cat;
this.agentID = new PersonalAgentID(this.name, this.category);
this.msgx.setOwner(this.agentID);
this.msgx = new MessageBox();
}
public void setObj(AgentThred i) {
this.obiettivo = i;
}
public void setThread(Thread i) {
this.trd = i;
}
@Override
synchronized public void run() {
{
//set a message to send
if(this.name == "Mercoledi"){
while(true){
// writer write a message in reader messagebox
System.out.println("writer wrote");
notifyAll(); //wake up the reader--doesn't work
//sleep(500)
}
}
else
while(true){
if(this.msgx.imEmpty()){ // if reader messagebox is empty
System.out.println("reader can't read");
wait(); //wait until writer put a message in the reader message box
}
else{
System.out.println("reader can read ");
//read the message
}
}
}
}
}
}
public static void main() {
AgentThred agt1 = null;
AgentThred agt2 = null;
MessageBox msg = new MessageBox();
}
agt1 = new AgentThred("Mercoledi","Addams");
agt2 = new AgentThred("Mano","Addams");
Thread t1 = new Thread(agt1);
Thread t2 = new Thread(agt2);
t2.start();
t1.start();
//I need a join here?
}
}
Возможно, вы захотите прочитать [Java Concurrency In Practice] (http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601), если вы собираетесь делать многопоточность. –