NotifyAll(), Wait() example

import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Akshay
*/
class Q {
int n;
boolean valueSet = false;
synchronized void get() throws InterruptedException {
wait();
System.out.println(Thread.currentThread().getName());
}
synchronized void put(String str) {
if(str.equals("akku"))
notifyAll();

}
}

class Producer implements Runnable {
Q q;
String str="";
Producer(Q q,String str) {
this.q = q;
this.str=str;
new Thread(this, "Producer").start();
}
public void run() {

q.put(str);

}
}

class Consumer implements Runnable {
Q q;
Consumer(Q q,int str) {
this.q = q;
new Thread(this, "Consumer "+str).start();
}
public void run() {
try {
q.get();
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}

}
}

class Test {
public static void main(String args[]) throws InterruptedException {
Q q = new Q();
for(int i=0;i<=10;i++){
new Consumer(q,i);
}
Thread.currentThread().sleep(3000);
System.out.println("Fail");
new Producer(q,"x");
Thread.currentThread().sleep(3000);
System.out.println("Pass");
new Producer(q,"akku");

System.out.println("Press Control-C to stop.");
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: