Create a new thread : Thread « J2ME « Java Tutorial






import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;

public class J2METhreadTest extends MIDlet implements CommandListener {

  private Form form = new Form("Thread Test");

  private StringItem text = new StringItem("Current Thread:", Thread.currentThread().getName());

  private Display display;

  public J2METhreadTest() {
    form.append(text);
    form.addCommand(new Command("Exit", Command.EXIT, 1));
    form.addCommand(new Command("New Thread", Command.SCREEN, 1));

    form.setCommandListener(this);

    display = Display.getDisplay(this);
  }

  public void startApp() {
    display.setCurrent(form);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command cmd, Displayable disp) {
    if (cmd.getLabel().equals("Exit")) {
      notifyDestroyed();
    } else {
      Thread runner = new Thread(new ThreadRunner(display));
      runner.start();
    }
  }
}

class ThreadRunner implements Runnable {
  Display display;

  ThreadRunner(Display display) {
    this.display = display;
  }

  public void run() {
    display.setCurrent(new Alert(Thread.currentThread().getName()));
    try {
      Thread.sleep(3000);
    } catch (Exception e) {
    }
  }
}








31.23.Thread
31.23.1.Create a new thread
31.23.2.Paint Canvas in a threadPaint Canvas in a thread
31.23.3.Thread in J2ME