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();
}
}
嗨,我编写了这个程序来了解线程是如何工作的。在这里,我将打印机类设为单例,并尝试通过实现 Runnable 在第二类 PrintThread 中实现线程。在这里,我覆盖了该Run(){}
方法,但在执行时 jvm 抛出一个错误,指出存在
PrintThread.run(Printer.java:31) 处的“Thread-0”(java.nullPointerException) 中的异常。
我试图用谷歌搜索它并阅读其他相关问题,但我仍然无法纠正问题