質問

When I am try to run a thread then it is giving following error

startApp threw an Exception
java.lang.NullPointerException
java.lang.NullPointerException
      at threadlearn.Midlet.startApp(Midlet.java:28)

MIDlet.java

public class Midlet extends MIDlet {
    ThreadClass th;

    public void startApp() {
        th.startThread();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

class ThreadClass implements Runnable{ 
    Thread t;

    ThreadClass() {

        t = new Thread(this);
    }

    public void startThread() {
        t.start();
    }

    public void run() {
        System.out.println("We are in Thread");
    }          
}
役に立ちましたか?

解決

As hoaz says, you need to initialize your object.

Also, your startThread() method is redundant. Why not just call start?

Anyway, it's considered bad practice to have threads start themselves. So I propose this rewrite of your code:

public class Midlet extends MIDlet {
 ThreadClass th = null;
 Thread myThread = null;

 public void startApp() {
  if (th==null) {
   th = new ThreadClass();
   myThread = new Thread(th);
  }
  myThread.start();
 }

 public void pauseApp() {
 }

 public void destroyApp(boolean unconditional) {
 }
}

class ThreadClass implements Runnable{ 

 ThreadClass() {
 }

 public void run() {
  System.out.println("We are in Thread");
 }          
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top