Programming The Midlet; Threads; Example - Siemens XT65 User Manual

Siemens cell phone accessories user manual
Hide thumbs Also See for XT65:
Table of Contents

Advertisement

Java User's Guide

13.2 Programming the MIDlet

122
13.2
Programming the MIDlet
The life cycle and structure of MIDlets are described in
TM
Java ME
, all of Java ME
such as those without any timer functions or those used only for tests and simple examples,
can be written without using threads. Longer applications should be implemented with threads.
13.2.1

Threads

Although small applications can be written without using threads longer applications should use
them. The Java programming language is naturally multi-threaded which can make a substan-
tial difference in the performance of your application. Therefore we recommend referring to
Java descriptions on threads before making any choices about threading models. Threads can
be created in two ways. A class can be a subclass of Thread or it can implement Runnable.
For example, threads can be launched in startApp() and destroyed in destroyApp(). Note that
destroying Java threads can be tricky. It is recommended that the developer read the Java doc-
umentation on threads. It may be necessary to poll a variable within the thread to see if it is still
alive.
13.2.2

Example

/* This example derives a class from Thread and creates two instances
* of the subclass. One thread instance finishes itself, the other one
* is stopped by the main application. */
package example.threaddemo;
import javax.microedition.midlet.*;
public class ThreadDemo extends MIDlet {
/* Member variables */
boolean
runThreads = true; // Flag for stopping threads
DemoThread thread1;
DemoThread thread2;
/* Private class implementing the thread to be started by the
* main application */
private class DemoThread extends Thread {
int loops;
public DemoThread(int waitTime) {
/* Store number of loops to execute */
loops = waitTime;
System.out.println("Thread(" + loops + "): Created");
}
public void run() {
System.out.println("Thread(" + loops + "): Started");
for (int i = 1; i <= loops; i++) {
/* Check if main application asked thread to die */
if (runThreads != true) {
System.out.println("Thread(" + loops + "): Stopped from outside");
/* Leave thread */
return;
}
wm_java_usersguide_v12
Confidential / Released
TM
's features, including threads, are available. Small applications,
// First instance of DemoThread
// Second instance of DemoThread
Page 121 of 123
s
Chapter
6. Since the MIDlets will run on
2008-02-25

Hide quick links:

Advertisement

Table of Contents
loading

This manual is also suitable for:

Ac65Ac75Xt75Tc65

Table of Contents