Threads and J2me

buninnateSoftware and s/w Development

Nov 18, 2013 (3 years and 7 months ago)

79 views

Threads and J2me

synchronisation

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

Thread states

ready

waiting

dead

running

sleeping

blocked

start

I/o completion

Sleep

Interval ends

Processor assigned

Issue I/O

complete

Sleep


wait

yield

Notify

notifyAll

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

Method 1 for thread creation

class MyThread extends Thread

{



public void run ()



{


for (int count = 1, row = 1; row < 5; row++, count++)


{



for (int i = 0; i < count; i++)


System.out.print ('*');


System.out.print ('
\
n');


}



}

}


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 < 20; i++)



System.out.println ("i = " + i + ", i * i = " + i * i);



}

}


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)


{


}



System.out.println (“Now print something


say a value from mt because your awake”);



}

}


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

Method 2 for Thread creation

class MyCanvas extends Canvas implements
Runnable{

Thread t;

…..


run(){




}


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 …..

Starting the thread

MyCanvas(MIDlet mid){


gamethread = new Thread(this);


}


start(){



gamethread.start();


}


run(){

}

Thread created

Canvas object sent in

Called from startApp say

Thread becomes live

Now run is invoked

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.


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.

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

synchronisation

public class Counter

{


private int counter; // data access needs synchronising



public synchronized int increment()


{ return ++counter; }



public synchronized int decrement()


{ if(
--
counter < 0 )


{ counter = 0; }


return counter;


}

}

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.

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

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.



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;
}

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
…….




continued


render(Graphics g)


{

g.setColor(0xffffff);


g.fillRect(0, 0, getWidth(), getHeight());


g.setColor(0x0000ff);


g.drawLine(…………);




flushGraphics();

}





Good reference


http://java.sun.com/developer/technicalAr
ticles/Threads/applet/


http://java.about.com/od/threadprogram
ming/


http://www.devdaily.com/Dir/Java/Articles
_and_Tutorials/Threads/


http://developers.sun.com/techtopics/mob
ility/midp/articles/threading2/


Look at the wireless toolkit examples and
identify the Threads used