Chapter
14—Multithreading and Animation
Section A, Introduction to Multithreading
Learning Objectives
· The concept of multithreading.
· How to use the Thread class
· How to use the sleep( ) method
· How to set the Thread priority
· How to use the Runnable interface
- When creating threads that are dependent on each other:
starvation or
deadlock may occur if a thread is waiting for information from
another thread.
-This could
be a serious problem in a complex applet when animation or some other thread is
waiting for data to be entered
by a user.
I. Program execution
A.
- A program is a list of instructions to the computer.
- Each CPU can only execute
one instruction at a time.
- Most computers only have one CPU, and
can therefore only execute one
instruction at a time.
- Multiple processors can execute
multiple instructions simultaneously.
- Each sequential list of instructions
to the computer is a thread.
B.
- The Java language allows multiple threads to be launched or
started.
- If they
are running on a multiple-CPU computer, the threads may run
simultaneously.
- On single CPU systems, the computer allocates a small amount
of time to each thread,
working on the first, dropping it, working on the second,
and so on until it cycles back to the first. This is called multithreading.
- The transitions
are so quick, that on most systems, multithreading appears to be
simultaneous execution.
C.
- Multithreading has become very important in the modern world of
connected, interactive and
multimedia computing.
II.
A.
- The Thread class is part of the java.lang package.
- A thread is not a full blown
program, but part of a complete program.
B.
To use threads, one must:
· Define a class that extends the thread class
Make sure you override the run( ) method.
· Write a program that uses that class
C.
You can achieve multithreading by declaring multiple threads. The
program
will then execute all of the threads.
III. The Thread’s life cycle
A.
The Thread has 5 states in its’ life cycle: new, ready, running,
inactive or
finished. Remember that in a multithreading/single CPU environment,
only
one statement at a time actually is being executed.
B.
The methods available for the Thread class are:
start( ) Starts
the Thread, starting run( )
stop( ) Stops
execution of the thread
suspend( ) Suspends
the Thread until the resume()
method is used
resume( ) Resumes
the thread where it left off
isAlive( ) Returns
a boolean to determine whether
the thread is currently
running
setPriority(int) Sets a priority for the Thread from 1
to 10
C.
The states of threads have the following characteristics:
· New – Created, but the only action available is start( )
· Ready – Thread has been started and is runnable, but may not be
running,
due to the fact that the CPU may be busy elsewhere
· Running – Thread is executing, and will run until it becomes
inactive or finishes
· Inactive – Thread is runnable but not running due to the fact
that either the
sleep( ) or suspend( ) methods have been called, or the CPU has
suspended
it to work on another Thread (only in a multithreading environment)
· Finished or Dead – When the Thread has finished all of its tasks
IV. The sleep( ) method
A.
The sleep(int) method allows the programmer to force a
thread to go into the inactive
stage for int number of milliseconds.
B.
When using the sleep( ) method, you must throw and catch the
InterruptedException, even though you need not do anything in the
catch.
V. Setting Thread priority
A.
- Setting Thread Priority is the ability to set rank in the
resource allocation to a Thread
by the CPU.
- The highest priority is 10, the lowest priority is 1, and
the default is 5.
- The Thread class has three constants, MIN_PRIORITY
(equal to 1), NORM_PRIORITY
(equal to 5), and MAX_PRIORITY (equal to 10).
- Priority of a Thread may be set to any integer from 1 to 10
through the
setPriority(int) method.
B.
When Threads with priorities are running in a multithreading
program, the
Threads with the highest priorities are run in rotation. When all
high priority
Threads are ended or inactive, the lower priority Threads are run.
C.
Programmers must be careful of starvation (a Thread cannot do
anything
because of other Threads’ priorities) or deadlock (Threads are
waiting for
other Threads to do something).
VI. The Runnable interface
A.
Java does not allow classes to inherit from multiple classes.
Therefore, a class may
not inherit from Applet and Thread.
B.
The Runnable interface can be implemented if multithreading is
desired in
an applet. The interface allows you to define the run() method, as
well as the
stop(), start() and destroy() methods.
examle : rolling ball
import java.applet.*;
import java.awt.*;
public class ball extends Applet
{
int x = 30, y = 30;
public void paint(Graphics g)
{
g.drawOval(x,30,80,80);
x += 20;
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
}
repaint();
}
}
example 2 :
import java.applet.*;
import java.awt.*;
public class animate extends Applet
{
private int index = 0;
int[] horiz={140,150,160,150,140};
int[] vert ={160,150,140,130,120};
private int sleep = 100;
public void start()
{
index = 0;
}
public void paint(Graphics g)
{
g.drawOval(10,30,80,80);
g.drawLine(85,110,85,210);
g.drawLine(85,210,40,310);
g.drawLine(85,210,130,310);
g.drawLine(85,140,40,160);
g.drawLine(85,140,horiz[index],vert[index]);
++index;
if (index == horiz.length)
index = 0;
try
{
Thread.sleep(sleep);
}
catch(InterruptedException e)
{
}
repaint();
}
}
Section B, Animation
Learning Objectives
· Creaing an animated figure
· Reducing figuring
· Using predrawn animated image objects
· Using Java’s garbage collection feature
· Using animation in a Web browser page
- Primitive animated figures can be included in an applet through
the use of the repaint() method
to repaint a frame, changing the image shape or size slightly with each repaint.
- You can reduce flicker by painting over the parts of the image
that are changing in the background
color and leaving the rest alone.
- If this method is used, remember that even
though the default background
of the appletviewer is white, the default background on a
web page is light gray.
- Images can be stored as separate files, usually in gif or jpeg
form.
- Gif images are the only
ones that can be animated at this time. It is safest to put the images in the
same folder
on the server where the HTML and class files are stored.
- Images can be created through any graphics program that supports
the gif and jpeg format,
either by screen capture, freehand drawing, or scanning.
I. Creating animated figures
A. Animation is created by showing, in rapid succession, a series
of images that differ
by only a small amount. As the images flow by, the viewer has the
impression of motion, even though they are viewing a series of
still images.
B. Using graph paper is the best way to create animation. Planning
the
successive positions of a graphical object assists in the realism
of the animation.
II. Reducing flickering
A. When an applet is drawn, and a new version of the graphical
images are
desired, to completely redraw the frame involves calling a number
of
methods, including the repaint(), update() and paint(). This can
cause flicker
on the screen, depending on the speed of the processor.
B. To avoid flicker, you can simply draw the objects (lines,
Strings, ovals and rectangles)
that need to disappear in the background color and draw the objects in
their new position in the
desired color.
III. Using predrawn animated Image objects
A. Predrawn images may be inserted into an applet. The types of
images that are generally
used at this time are:
· Gif files (Graphics
Interchange format) – file
extension .gif
· Jpeg files (Joint
Photographic Experts Group)
– file extension .jpeg or .jpg
Some gif files are animated gifs: a series of gifs shown in rapid
succession, giving the
appearance of motion, but stored as one file.
B. To use an image requires a two step process: creating an Image
object and placing the object on the page.
Creating an Image object:
Image
imageName = getImage(URL, filename);
For images on the Internet, the URL is
getDocumentBase(http://some.web.address)
For images on the same drive and folder as the program, the URL is
getDocumentBase( )
The filename is the filename of the file, such as "yoyo.gif"
Placing the Image object:
graphicsObject.drawImage(imageName, x, y, ImageObserver);
imageName is the name of the image created with the getImage()
method
x is the x-coordinate of the upper-left hand corner of the image
placement
y is the y-coordinate of the upper-left hand corner of the image
placement
ImageObserver is an interface that updates images as they load;
with
applets, use this
IV. Using Java’s garbage collection
A. Java’s garbage collection automatically sweeps through the
memory and frees memory
that is occupied by null references, unneeded objects, out-of-scope
objects, and objects that are
only partially constructed due to Exceptions.
B. Garbage collection is a very low priority Thread that only runs
when system response is degraded. You can specifically run it with the
command:
System.gc(
);
V. Using animation in a web browser page
A. HTML is the language of the Internet and is interpreted by
browsers (such as Netscape
Navigator or Microsoft Internet Explorer) to create web pages. An
applet can be inserted into a
Web page and viewed on a browser. There are many
"tags" in HTML that allow you to place and format text, images,
applets and
other objects on the page.
B. Heading ranging from <H1> (the largest) to <H5> (the
smallest) may be
placed on a page, along with multiple applets.