(1)(2)这两个地方写成 Person p = new Person() ;和Student s = new Person() ;就出Exception in thread "main" java.lang.StackOverflowError,为什么??public class Runnable_Test { public static void main(String[] arg) {
Person p1 = new Person() ;
Student s1 = new Student() ;
Thread thread = new Thread(p1) ;
thread.start() ;
Thread thread1 = new Thread(s1) ;
thread1.start() ;
}
}class Person implements Runnable {
private String names ;
Person p = null ; //**************************(1)
public void run() {
p = new Person();
for(int i=0; i<100; i++) {
p.setNames("Person" + i) ;
System.out.println("PersonName---->" + p.getNames()) ;
}
}
public void setNames(String names) {
this.names = names ;
}
public String getNames() {
return this.names ;
}
}class Student extends Person implements Runnable {
private int age ;
Student s = null ; //**************************************(2)
public void run() {
s = new Student() ;
for(int i=0; i<100; i++) {
s.setNames("Student:" + i) ;
s.setAge(i) ;
System.out.println("StudentName~~~~" + s.getNames());
System.out.println("StudentAge*******" + s.getAge());
}
}
public void setAge(int age) {
this.age = age ;
}
public int getAge() {
return this.age ;
}
}
Person p1 = new Person() ;
Student s1 = new Student() ;
Thread thread = new Thread(p1) ;
thread.start() ;
Thread thread1 = new Thread(s1) ;
thread1.start() ;
}
}class Person implements Runnable {
private String names ;
Person p = null ; //**************************(1)
public void run() {
p = new Person();
for(int i=0; i<100; i++) {
p.setNames("Person" + i) ;
System.out.println("PersonName---->" + p.getNames()) ;
}
}
public void setNames(String names) {
this.names = names ;
}
public String getNames() {
return this.names ;
}
}class Student extends Person implements Runnable {
private int age ;
Student s = null ; //**************************************(2)
public void run() {
s = new Student() ;
for(int i=0; i<100; i++) {
s.setNames("Student:" + i) ;
s.setAge(i) ;
System.out.println("StudentName~~~~" + s.getNames());
System.out.println("StudentAge*******" + s.getAge());
}
}
public void setAge(int age) {
this.age = age ;
}
public int getAge() {
return this.age ;
}
}
一旦线程run起来之后,A2部分就会运行,A2的运行将导致一个person的实例化,person的实例化要经过A1并且运行它.A1被运行后也会造成一个person实例化的过程,这样就等于一直在实例化,所以stack overflow了.至少看起来是这样的.