I want to establish communication between 2 threads like this :
The first Thread(Sender
) sends to the second Thread(Receiver
) an Integer and Receiver
display the square of this Integer.
Here is my code :
Carre.java(main) :
public class Carre {
static Boolean msgArrived = Boolean.FALSE ;
static int n ;
public static void main(String[] args) {
Thread sender = new Thread(new Sender()) ;
Thread receiver = new Thread(new Receiver()) ;
sender.start() ;
receiver.start() ;
}
public int getN() {
return n;
}
}
Sender.java :
import java.util.Random;
public class Sender implements Runnable {
@Override
public void run() {
while(Carre.msgArrived == Boolean.TRUE) {
try {
wait() ;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0; i < 10; i ++) {
Random ran = new Random() ;
Carre.n = ran.nextInt(100) ;
Carre.msgArrived = Boolean.TRUE ;
notifyAll() ;
}
}
}
Receiver.java
public class Receiver implements Runnable {
@Override
public void run() {
while(Carre.msgArrived == Boolean.FALSE) {
try {
wait() ;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Carre.n * Carre.n) ;
Carre.msgArrived = Boolean.TRUE ;
notifyAll() ;
}
}
& When i try to execute my code I receive this error message :
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at Receiver.run(Receiver.java:12)
at java.lang.Thread.run(Thread.java:636)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at Sender.run(Sender.java:19)
at java.lang.Thread.run(Thread.java:636)