我的代码如下。 创建MyThread对象后,控件将直接转到第1行(在代码中注释),然后抛出NullPointerException。 这种行为的原因是什么? 我想知道为什么s未初始化,我正在使用构造函数并在为其创建对象时传递值?
public class ClassOne {
public static void main(String[] args) {
MyThread t = new MyThread("name");
Thread tone = new Thread(t);
tone.start();
for (int i =0; i<=10;i++) {
System.out.println(i);
}
}
}
class MyThread implements Runnable {
String s;
MyThread (String s) {
this.s=s;
System.out.println("Constructor");
}
char[] ch = s.toCharArray(); // line 1
public void run() {
for (char c : ch) {
System.out.println(c);
}
}
}