Saturday, 24 August 2013

wait() and notify() methods

wait() and notify() methods

I have two classes First and Second. In class First I just run two
threads. Class Second has two methods, one for changing static variable
array, and one for reading array after changing. I want to do this whit
wait and notify.
class First{
public static void main(String[] args){
Second s1 = new Second(1);
Second s2 = new Second(2);
s1.start();
s2.start();
}
}
class Second extends Thread{
private static int[] array = {1, 2, 3};
private int number;
Second(int number){
this.number = number;
}
public void run(){
change();
System.out.println("Out of change: " + getName());
read();
}
public synchronized void change(){
if(array[0] != 1)
return;
System.out.println("Change: " + getName());
for(int i = 0; i < 10; i++)
array[0] += i;
notify();
}
public void read(){
try{
System.out.println("Waiting for change:" + getName());
wait();
}
catch(InterruptedException ie){
System.out.println("IE");
}
System.out.println("Score: " + array[0]);
}
}
I'm getting IllegalMonitorException. How to solve that problem? Do I must
use lock variable?

No comments:

Post a Comment