I am new to Thread. I have created two classes name A and B as follow-
public class A {
private B b;
public void setB(B b) {
this.b = b;
}
synchronized void foo() {
b.foo();
System.out.println("Hi A");
}
}
public class B {
private A a;
public void setA(A a) {
this.a = a;
}
synchronized void foo() {
a.foo();
System.out.println("Hi B");
}
}
Now i have created two other classes which implements Runnable interface.
public class AThread implements Runnable{
private A a;
public AThread(A a){
this.a = a;
}
@Override
public void run() {
a.foo();
}
}
public class BThread implements Runnable {
private B b;
public BThread(B a){
this.b = b;
}
@Override
public void run() {
b.foo();
}
}
In main method, i have written the following code-
public static void main(String args[]) {
A a = new A();
B b = new B();
a.setB(b);
b.setA(a);
Runnable r1 = new AThread(a);
Runnable r2 = new BThread(b);
Thread t1 = new Thread(r1);
t1.start();
}
When i am running this code, i got the following exception.
Exception in thread "Thread-0" java.lang.StackOverflowError
at student.B.foo(B.java:21)
at student.A.foo(A.java:21)..
Can any one explain what is the route cause of it and how can i solve it?
foo()method of your objects.