[英]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.