我是 Thread 新手。我创建了两个类,名称为 A 和 B,如下 -
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 接口(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();
}
}
在main方法中,我编写了以下代码-
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)..
谁能解释一下它的路由原因是什么以及如何解决它?
最佳答案
你期望什么?
您在 A
中有一个 foo()
方法,调用 B
中的 foo()
方法,该方法调用A
中的 foo()
方法,依此类推,直到堆栈溢出。
您可以通过避免循环方法调用来解决这个问题。
关于java - Java中的堆栈溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44025689/