Threads and Media

peachpuceAI and Robotics

Nov 6, 2013 (4 years and 1 month ago)

88 views

(c) 2008 E.S.Boese All Rights Reserved.

Threads and Media

Chapter 8
-

Lecture Slides

1

(c) 2008 E.S.Boese All Rights Reserved.

Threads


Multi
-
processing: 2 or more things occurring at the same time



When we run a program, a single thread automatically starts
to run the program.



To run two or more things simultaneously, we need to create a
second (or more) thread(s).



Ideal for slideshows, progress bars, animation, game
programming



For example, if we want to perform a slideshow
while

the user
is typing inside a, we need to use a separate thread for the
slideshow.

JTextArea


If we didn't use a second thread, the applet would hang while
we ran through the code for the slideshow.


2

(c) 2008 E.S.Boese All Rights Reserved.

Threads


steps to make it work


There are four steps to get
Thread

to work:


1. The class needs to implement the
Runnable

interface.


implements Runnable


2. Create a
Thread


Thread runner;



runner = new Thread( this );


3. Start the
Thread



runner.start( );


4. Create a method named
run



public void run( )


{


}

When we use Threads we
put the code inside the
run

method.

3

(c) 2008 E.S.Boese All Rights Reserved.

run( ) method


Code goes inside the
run

method.

Usually we want the code to loop. We can set up the loop as an infinite loop.


public void run( )

{


while( true )


{



// code


}

}



Use the method
sleep

in the
Thread

class to simulate a
delay
:

(This is the proper way to delay, unlike the for loop we used earlier in the book)



Thread.sleep( delayInMilliseconds );

OR

thread.sleep( delayInMilliseconds );

// thread variable



To use the sleep method, we need to put it within a
try ... catch
block to catch any
exceptions (errors) that may may occur

(usually put the try...catch around the while(true) loop):


try {


Thread.sleep( delayInMiliseconds );

} catch( Exception exc ) { }


infinite loop


always true!

4

Applet methods

Method

Header

Description

public

void

init(

)

Initialize

our

applet
;

called

only

once

public

void

start(

)

Starts

our

applet

running
;

start

up

necessary

threads

public

void

stop(

)

Applet

is

no

longer

being

displayed
;

stop

our

threads

from

running

(c) 2008 E.S.Boese All Rights Reserved.

5

(c) 2008 E.S.Boese All Rights Reserved.

Examples


Slideshow inside main applet class


see Slideshow.java



Slideshow in a separate class


see Slides.java and SlidesApplet.java




Animation is done by redrawing


see Wink.java and Smile.java


See AnimateThreads.java


Animation Example

6

Game play
-

process

(c) 2008 E.S.Boese All Rights Reserved.

7

Game play


offscreen images

(c) 2008 E.S.Boese All Rights Reserved.

8

(c) 2008 E.S.Boese All Rights Reserved.

MediaTracker


Use for loading images and sound files
before the applet starts


Ensures everything is loaded properly before
the applet runs


Prevents empty screens or missing
graphics/media

9

MediaTracker

import

java.awt
.*;

import

javax.swing
.*;

public

class

MediaTrackerEx

extends

JApplet

{


Image one, two, three, four;


MediaTracker

imgTracker
;


public

void

init
()


{



loadImages
();


}


public void start()


{



try



{




imgTracker.waitForAll
();



}catch (Exception e)



{ }


}


public

void

loadImages
()


{



one =
getImage
(
getCodeBase
(
), "
one.gif
");



two =
getImage
(
getCodeBase
(), "
two.gif
");



three =
getImage
(
getCodeBase
(), "
three.gif
");



four =
getImage
(
getCodeBase
(), "
four.gif
");



imgTracker.addImage
(one, 1);



imgTracker.addImage
(two, 2);



imgTracker.addImage
(three, 3);



imgTracker.addImage
(four, 4);


}


}


(c) 2008 E.S.Boese All Rights Reserved.

10

(c) 2008 E.S.Boese All Rights Reserved.

Audio


11

Audio Files


Java can play the following audio types:


.au

(Sun Audio)


.wav

(Windows Wave)


.aif

or
.aiff

(Macintosh AIFF)


.mid

(Musical Instrument Digital Interface (MIDI)


.rmf

Note: mp3 is NOT supported
in the Java API. However,
There are libraries you can
download and use

Note: wav files from your
CDs are HUGE! Won’t run
well


only use small WAV
files

Audio



AudioClip clip;


clip = getAudioClip( getCodeBase( ), audioFilename );


clip.play( );



There are three methods we can call on our
AudioClip


play


play the sound file once through


loop


play the sound file continually


stop


stop playing the file

getCodeBase( )

works same for
images as audio
files

Audio

import

java.awt.*;

import java.applet.*;

import

javax.swing.*;

public class

AudioPlay
extends

JApplet

{


String audioFilename = "mySounds.mid";


AudioClip ac;


public void

init( )


{



ac = getAudioClip( getCodeBase( ), audioFilename );



ac.play( );


}

}

Audio

To have sound clip loop:


get an
AudioClip


call the
loop( )

method


import

java.awt.*;

import

java.applet.*;

import

javax.swing.*;

public class

AudioPlay
extends

JApplet

{


String audioFilename = "mySounds.mid";


AudioClip ac;


public void

init( )


{



ac = getAudioClip( getCodeBase( ), audioFilename );



ac.
loop( );


}

}

Audio: Need for
stop( )


See Example


Each button starts an audio file playing


If the previous one isn’t stopped first,

then the new one plays on TOP of the other one


This is usually not desired





However, some applications want this
technique


(see example of Singing Horses on Internet at:


http://svt.se/hogafflahage/hogafflaHage_site/Kor/hestekor.swf



stop method

import

java.awt.*;

import

java.applet.*;

import

java.awt.event.*;

import

javax.swing.*;

public class

LoopAudio
extends

JApplet

{


String audioFilename = "happyDaze.wav";


AudioClip ac;


public void

init( )


{



ac = getAudioClip( getCodeBase( ), audioFilename );



ac.loop( );


// loop instead of play


}



public void

stop( )


{




// can't stop it if it isn't running, check first



if( ac != null )




ac.stop( );


}

}


Stop playing audio when
user leaves the applet:


Write a
stop

method


(c) 2008 E.S.Boese All Rights Reserved.

Timers


18

(c) 2008 E.S.Boese All Rights Reserved.

Timers


Timers are useful for repeating steps at particular intervals.


Examples: progress bars, custom clocks and timed animation,

tooltips, blinking cursor



Timers are based on
event

processing,


Important that the code to be run from a
Timer

event can be
executed
quickly

to enable the system to handle the next event.
(Threads do not have this limitation and therefore are ideal for
more time
-
intensive code processing).



Create a
Timer

object by specifying the delay count in
milliseconds and the listener for the
ActionEvent
:


Timer timer;

timer = new Timer( delay, this );

19

(c) 2008 E.S.Boese All Rights Reserved.

Timers


Similar to threads, we then need to start the timer:


timer.start( );



After the delay in milliseconds, the
actionPerformed

method is
called. Therefore, just like when we listen for events on buttons, we
need to implement the
ActionListener
.




public void actionPerformed( ActionEvent ae )


{




Object src = ae.getSource( );




if ( src instanceof Timer )




// do something since Timer expired




else if ( src instanceof JButton )




// do something based on a button click



}

20

(c) 2008 E.S.Boese All Rights Reserved.

Timers


There are five steps to get
Timer

to work:

1. Import the package to handle
ActionEvent

events:


import java.awt.event.*;


2. Specify that we're listening for events:


public class xyz extends JApplet
implements ActionListener


3. Create a
Timer

object


Timer timer;

timer = new Timer( delay, this );


4. Start the timer:

timer.start( );


5. Add an
actionPerformed

method:


public void actionPerformed( ActionEvent ae )


{


Object src = actionEvent.getSource( );


if ( src instanceof Timer )



...


else if ( src instanceof JButton )



...

}

6. (
Optional) Stop the Timer


timer.stop( );


21

TimedClock Example

import

java.awt.*;

import

java.awt.event
.*;

import

javax.swing
.*;

public

class

TimedClock

extends

JApplet

implements

ActionListener

{


JLabel

countdown;


int

count = 10;


Timer
timer
;


int

DELAY = 800;


// delay in
miliseconds




public

void

init( )


{



setLayout
(
new

FlowLayout
( ) );



countdown =
new

JLabel
(
String.
valueOf
( count ) );



countdown.setFont
(
new

Font(
"Serif"
,
Font.
BOLD
, 46 ) );



add( countdown );



timer = new Timer( DELAY, this );


timer.start
( );


}


public

void

actionPerformed
(
ActionEvent

ae

)


{




Object
src

=
ae.getSource
( );




if

(
src

== timer

&& count > 0 )




{





count = count
-

1;





countdown.setText
(
String.
valueOf
( count ) );




}




if

( count == 0 )





countdown.setText
(
"Blast
-
off!"

);


}

}


(c) 2008 E.S.Boese All Rights Reserved.

22

(c) 2008 E.S.Boese All Rights Reserved.

Summary


Threads


MediaTracker


Audio


Timers

23