Title: Threads and J2me
1Threads and J2me
2What are threads
- A thread is a path of execution through a program
- Single threaded programs have one path of
execution - multi-threaded programs have two or more paths of
execution - Single threaded programs can perform only one
task in sequence before starting another
3Thread states
start
I/o completion
ready
Processor assigned
running
Issue I/O
yield
blocked
Notify notifyAll
complete
wait
Sleep
dead
waiting
sleeping
Sleep Interval ends
4Two Methods
- In Java, thread instances can be created using
two techniques - implement the java.lang.Runnable interface
- Inherit from the java.lang.Thread class
5Method 1 for thread creation
class MyThread extends Thread  public void
run ()Â Â Â Â Â Â Â Â for (int count 1, row 1
row lt 5 row, count)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â for
(int i 0 i lt count i)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â System
.out.print ('') System.out.print
('\n')Â Â Â Â Â Â Â Â
6Starting a thread from the main thread
class UseThread  public static void main
(String args)Â Â Â Â Â Â Â Â MyThread mt new
MyThread ()Â Â Â Â Â Â mt.start ()Â Â Â Â Â Â for (int i
0 i lt 20 i)Â Â Â Â Â Â Â Â Â Â System.out.println
("i " i ", i i " i i)Â Â
7Allow others to function
class Calculate   public static void main
(String args)Â Â Â Â Â Â Â Â MyThread mt new
MyThread ()      mt.start ()      try     Â
          Thread.sleep (10) // Sleep for 10
milliseconds            catch
(InterruptedException e)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Sy
stem.out.println (Now print something say a
value from mt because your awake)Â Â
8Alive?
- When a program calls Thread's start() method, a
time period (for initialization) - passes before run() is called.
- After run() returns, a time period passes before
the JVM cleans up the thread. - The JVM considers the thread to be alive
immediately - prior to the thread's call to run()
- during the thread's execution of run()
- immediately after run() returns.
- During that interval, Thread's isAlive() method
returns a Boolean true value. - Otherwise, that method returns false
9Method 2 for Thread creation
- class MyCanvas extends Canvas implements
Runnable - Thread t
- ..
- run()
-
10Thread
- Within the constructor create the thread and pass
the canvas class in. When the Thread is then told
to start the run() method will be invoked ..
11Starting the thread
Called from startApp say
MyCanvas(MIDlet mid) gamethread new
Thread(this) start() gamethread.start()
run()
Thread created
Canvas object sent in
Thread becomes live
Now run is invoked
12No stop() or interrupt()
- Once started a J2ME thread lives until it
intentionally or unintentionally - exits the run() method
- The system may also terminate running threads
when the application - stops running
- There is no way for one thread to force another
thread to stop - You can stop a live thread only by convincing it
to terminate itself.
13JAVA uses the concept of a Monitor
- Limits the threads acting within an object - they
queue up - Each method on an object which accesses protected
resources is marked as synchronized. - The monitor is a fence around the object.
- Each synchronized method is an automatically
controlled gate in that fence.
14synchronization
- Interacting threads must use thread
synchronization to control who can read or write
shared data at any given time - A monitor acts as a gatekeeper, ensuring that
only one thread at a time has access to data
15synchronisation
public class Counter private int counter
// data access needs synchronising public
synchronized int increment() return
counter public synchronized int
decrement() if( --counter lt 0 )
counter 0 return counter
16Other uses of synchronized
- Further use of the synchronized statement
- The synchronized statement may be used in a
method to synchronize an arbitrary block of code. - A static method may be labeled as synchronized,
in which case the monitor it attached to the
enclosing class.
17Threads and the game loop
- The Midlet is started and listens for user
commands - It is sent to the Canvas class
- If the canvas already inherits then the logical
choice for thread setup is the Runnable interface - class GameCanvas extends Canvas implements
Runnable
18Threads
- Typically a game will need three threads..
- one to capture user interaction,
- two to paint the images on the screen,
- three to implement the game logic and sprite
manipulation. - The first two are automatically implemented (MIDP
2.0), - the third will need to be created by the
programmer. -
19The game Loop
import javax.microedition.lcdui. import
javax.microedition.lcdui.game. public class
MyGameCanvas extends GameCanvas implements
Runnable private boolean mStart
int mDelay // set up
variables for game public MyGameCanvas()
super(true) //
initialise variables public
void start() mStart true
Thread t new Thread(this)
t.start() public void stop()
mStart false
20continued
public void run() Graphics g
getGraphics() while (mStart true)
input()
render(g) try
Thread.sleep(mDelay) catch
(InterruptedException ie)
private void input() int
keyStates getKeyStates() if
((keyStates LEFT_PRESSED) ! 0)
//set variable values.
21continued
render(Graphics g) g.setColor(0xffffff)
g.fillRect(0, 0, getWidth(), getHeight())
g.setColor(0x0000ff) g.drawLine()
flushGraphics()
22Good reference
- http//java.sun.com/developer/technicalArticles/Th
reads/applet/ - http//java.about.com/od/threadprogramming/
- http//www.devdaily.com/Dir/Java/Articles_and_Tuto
rials/Threads/ - http//developers.sun.com/techtopics/mobility/midp
/articles/threading2/ - Look at the wireless toolkit examples and
identify the Threads used