Threads and J2me - PowerPoint PPT Presentation

1 / 22
About This Presentation
Title:

Threads and J2me

Description:

System.out.println ('Now print something say a value from mt because your awake' ... During that interval, Thread's isAlive() method returns a Boolean true value. ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 23
Provided by: jab88
Category:
Tags: j2me | method | setup | threads

less

Transcript and Presenter's Notes

Title: Threads and J2me


1
Threads and J2me
  • synchronisation

2
What 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

3
Thread 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
4
Two Methods
  • In Java, thread instances can be created using
    two techniques
  • implement the java.lang.Runnable interface
  • Inherit from the java.lang.Thread class

5
Method 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')        
6
Starting 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)  
7
Allow 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)  
8
Alive?
  • 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

9
Method 2 for Thread creation
  • class MyCanvas extends Canvas implements
    Runnable
  • Thread t
  • ..
  • run()

10
Thread
  • 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 ..

11
Starting 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
12
No 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.

13
JAVA 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.

14
synchronization
  • 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

15
synchronisation
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

16
Other 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.

17
Threads 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

18
Threads
  • 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.

19
The 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
20
continued
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.
21
continued
render(Graphics g) g.setColor(0xffffff)
g.fillRect(0, 0, getWidth(), getHeight())
g.setColor(0x0000ff) g.drawLine()
flushGraphics()
22
Good 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
Write a Comment
User Comments (0)
About PowerShow.com