public class Printer {
static Printer obj =null;
private Printer(){}
public static Printer getInstance(){
if(obj==null){
Printer pr=new Printer();
}
return obj;
}
void print(String msg){
System.out.println("["+msg);
try {
Thread.sleep(1000);
} catch(InterruptedException c) {
c.printStackTrace();
}
System.out.println("]");
}
}
class PrintThread implements Runnable {
Printer p;
String msg;
PrintThread(Printer p,String msg) {
this.p=p;
this.msg=msg;
}
public void run() {
p.print(msg);//Getting error in this line
}
}
//Deploying main class
public class Execution {
public static void main(String[] args) {
Printer pr=Printer.getInstance();
Thread t1=new Thread(new PrintThread(pr,"java"));
t1.start();
PrintThread r=new PrintThread(pr,"javadeveloper");
Thread t2=new Thread(r);
t2.start();
}
}
嗨, 我已經編寫了這個程序,以瞭解線程是如何工作的。在這裏,我將Printer類作爲單例,並嘗試通過實現Runnable在第二類PrintThread中實現線程。在這裏,我overrided的Run(){}
方法,但在執行的時的JVM是引發錯誤說有一個線程異常(java.nullPointerException)
在異常「線程0」(java.nullPointerException)在PrintThread.run(Printer.java :31)。
我想谷歌它,也閱讀等相關的問題,但我仍不能糾正問題