0
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) 中的异常。

我试图用谷歌搜索它并阅读其他相关问题,但我仍然无法纠正问题

4

6 回答 6

5
static Printer obj =null;
    private Printer(){}
     public static Printer getInstance(){
         if(obj==null){
             Printer pr=new Printer();
         }
     return obj;  
     }

您创建一个新Printer对象,但返回 null 值。

正确的:

static Printer obj = null;
private Printer(){}

public static Printer getInstance(){
 if(obj == null){
  obj = new Printer();
 }
 return obj;
}
于 2013-08-19T09:18:44.793 回答
3

更正您的getInstance实施:

public static Printer getInstance() {
    if(obj==null) {
         obj = new Printer(); // don't create local variable
    }
return obj;  
}
于 2013-08-19T09:18:50.407 回答
3
Printer pr=new Printer();

将其更改为

  obj=new Printer();
于 2013-08-19T09:19:47.370 回答
3

You are not correctly initializing the Printer variable: Printer.getInstance() always return null, what leads to a NullPointerException. Do this instead:

public static Printer getInstance() {
     if (obj == null) {
         obj = new Printer();
     }
     return obj;
}
于 2013-08-19T09:21:12.320 回答
1
Printer pr=new Printer();

此代码创建打印机的新对象,但没有使用此对象,并且obj对象在其生命周期范围内为 null

建议的代码

public static Printer getInstance(){
     if(obj==null){
    obj=new Printer();            // Printer pr=new Printer();  /// here it's wrong
     }
 return obj;  
 }
于 2013-08-19T09:28:34.480 回答
0

您需要正确实现单例类。将构造函数声明为私有方法。实现一个返回同一个类的实例的静态方法。还以线程安全的方式实现实例的创建。喜欢

打印机 p= 新打印机();

于 2013-08-19T09:48:32.583 回答