2013-08-19 78 views
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(); 
    } 
} 

嗨, 我已經編寫了這個程序,以瞭解線程是如何工作的。在這裏,我將Printer類作爲單例,並嘗試通過實現Runnable在第二類PrintThread中實現線程。在這裏,我overrided的Run(){}方法,但在執行的時的JVM是引發錯誤說有一個線程異常(java.nullPointerException)

在異常「線程0」(java.nullPointerException)在PrintThread.run(Printer.java :31)。

我想谷歌它,也閱讀等相關的問題,但我仍不能糾正問題

回答

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

您創建一個新Printer對象,但返回空值。

正確:

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

public static Printer getInstance(){ 
if(obj == null){ 
    obj = new Printer(); 
} 
return obj; 
} 
3

糾正你getInstance實現:

public static Printer getInstance() { 
    if(obj==null) { 
     obj = new Printer(); // don't create local variable 
    } 
return obj; 
} 
3
Printer pr=new Printer(); 

改變這

obj=new Printer(); 
3

你是不是正確初始化Printer變量:Printer.getInstance()總是返回null,什麼導致了NullPointerException。做到這一點,而不是:

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

此代碼創建打印機的新對象,但不使用該 和OBJ對象是具有空爲他的一生範圍

建議代碼這個

public static Printer getInstance(){ 
    if(obj==null){ 
    obj=new Printer();   // Printer pr=new Printer(); /// here it's wrong 
    } 
return obj; 
} 
0

您需要正確實現單例類。聲明一個構造函數作爲私有方法。 實現一個返回同一個類的實例的靜態方法。還以線程安全的方式實現實例的創建。像

Printer p = new Printer();