hello , as u know wait() and notify() will not thow an exception if the method that calls them has the lock , or esle i misundrestood java :P
this is the code that throws (unwanted) exceptions :
(or u can download it from :
at this link it has the spaces )
i put the /* */ to see if the 2 run() were synchronidez and they were, too se , just put /* */ the rest of the run()1s body for each class , and u will see that only one run() will print.
this is the code that throws (unwanted) exceptions :
(or u can download it from :
at this link it has the spaces )
Code:
public class WaitingForThread {
public static void main (String []args) {
String []message = {"msg 1","msg 2","msg 3"
,"msg 4","msg 5","msg 6","msg 7","msg 8","msg 9","msg 10"};
boolean begin[] = new boolean [10];
Client client = new Client(begin);
Producer producer = new Producer(message,client,begin);
new Thread(client).start();
new Thread(producer).start();
}
}
class Producer implements Runnable {
String message[] = new String [10];
int msgNumber;
Client client;
boolean begin[];
Producer (String [] message, Client client,boolean [] begin) {
this.message = message;
this.client = client;
this.begin = begin;
}
public void run() {
synchronized (this.client) {
while (msgNumber <message.length) {
try {
Thread.sleep(200);
}
catch(Exception e) {e.printStackTrace();}
client.message[msgNumber] = message[msgNumber];
System.out.print("\n\n Producer passed message nr "
+msgNumber);
begin[msgNumber] = true;
try {
notify();
System.out.print("\n\n the producer waits now..");
wait();
}
catch (Exception e) {e.printStackTrace();}
msgNumber++;
}
/* while(true) {
try {
Thread.sleep(200);
System.out.print("\n\n producer `s run()");
}
catch (Exception e) {};
}
*/
}
}
}
class Client implements Runnable{
int msgNumber;
boolean begin[];
String [] message = new String[10];
Client(boolean []begin) {
this.begin = begin;
}
synchronized public void run () {
while (true) {
while (!begin[msgNumber]) {
try {
System.out.print("\n\n the client is waiting for the Producer\n\n");
// System.out.print("\n\n begin["+msgNumber+"] = "+begin[msgNumber]);
Thread.sleep(3000);
notify();
wait();
}
catch (Exception e) {e.printStackTrace();}
}
if (message[msgNumber]!=null) {
System.out.print("\n\n client is thinking..");
try {
Thread.sleep(2000);
}
catch(Exception e) {e.printStackTrace() ;}
System.out.print("\n\n client says : \""+message[msgNumber++]
+"\"\n\n");
try {
notify();
System.out.print("\n\n client is waiting..");
wait();
}
catch (Exception e) {e.printStackTrace();}
}
/* while(true) {
try {
Thread.sleep(200);
System.out.print("\n\n clinet `s run ()");
}
catch (Exception e) {};
}
*/
}
}
}
Comment