试图在J2ME MIDlet中创建一个Thread

时间:2014-03-13 12:39:28

标签: java multithreading java-me midlet

当我尝试运行一个线程时,它会发出以下错误

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");
    }          
}

1 个答案:

答案 0 :(得分:0)

正如hoaz所说,你需要初始化你的对象。

此外,您的startThread()方法是多余的。为什么不直接打电话?

无论如何,让线程自己开始被认为是不好的做法。所以我建议重写你的代码:

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");
 }          
}