실용 신안입니다. 다음과 같이 두 클래스 A와 B를 만들었습니다.Java에서 스택 오버플로 예외가 발생했습니다.
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");
}
}
이제 Runnable 인터페이스를 구현하는 두 개의 다른 클래스를 만들었습니다.
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();
}
}
주요 방법에서, 나는이
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();
}
이 코드를 실행하고 코드 -, 나는 다음과 같은 예외를 가지고 다음 작성했습니다.
Exception in thread "Thread-0" java.lang.StackOverflowError
at student.B.foo(B.java:21)
at student.A.foo(A.java:21)..
경로의 원인이 무엇인지 설명하고 해결할 수 있습니까?
개체의'foo()'메서드를 호출하면 무한 재귀 호출 시퀀스가 발생합니다. –