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();
}
}
Hi,
I have written this program to understand that how the thread works. Here i made Printer class as singleton and tried to implement thread in second class PrintThread by implementing Runnable. Here i overrided the Run(){} method but at the the time of execution the jvm is throwing an error saying that there is a
Exception in "Thread-0"(java.nullPointerException) at PrintThread.run(Printer.java:31).
I tried to google it and also read other related question but still i am not able to rectify the problem