繁体   English   中英

尝试在J2ME MIDlet中创建线程

[英]Trying to create a Thread in J2ME 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");
    }          
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM