Lập trình Java - Phần 4
Chia sẻ bởi Nguyễn Bùi Minh Tâm |
Ngày 19/03/2024 |
13
Chia sẻ tài liệu: Lập trình Java - Phần 4 thuộc Công nghệ thông tin
Nội dung tài liệu:
11/20/2009
Võ Phương Bình - ITFAC - DLU
1
Part IV: Developing Comprehensive Projects
Chapter 10: Exception Handling
Chapter 11: Multithreading
Chapter 12: Multimedia
Chapter 13: Input and Output
Chapter 14: Networking
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 10
Exception Handling
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
Exceptions and Polymorphism
The finally clause
Resource Management
Uncaught Exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
What Exceptions are For
To handle Bad Things
I/O errors, other runtime errors
when a function fails to fulfill its specification
so you can restore program stability (or exit gracefully)
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
What Exceptions are For, cont
To force you to handle Bad Things
because return codes can be tedious
and sometimes you’re lazy
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
Example File I/O
public FileReader(String fileName)
throws FileNotFoundException
public void close() throws IOException
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
import java.io.*;
class OpenFile
{
public static void main(String[] args)
{
if (args.length > 0)
{
try
{
// Open a file:
FileReader f =
new FileReader(args[0]);
System.out.println(args[0]
+ " opened");
f.close();
}
catch (IOException x)
{
System.out.println(x);
}
}
}
}
Example File I/O, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
What Exceptions are For, cont
To signal errors from constructors
because constructors have no return value
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
What Exceptions are NOT For
NOT For Alternate Returns:
e.g., when end-of-file is reached:
while ((s = f.readLine()) != null) …
Exceptions are only for the exceptional!
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Catching Exceptions
Wrap code to be checked in a try-block
checking occurs all the way down the execution stack
try-blocks can be nested
control resumes at most enclosed matching handler
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Catching Exceptions, cont
Place one or more catch-clauses after try-block
runtime system looks back up the call stack for a matching handler
subclass types match superclass types
catching Exception catches everything (almost)
handlers are checked in the order they appear
place most derived types first!
execution resumes after last handler
if you let it (could branch or throw)
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
Throwing Exceptions
Must throw objects derived (ultimately) from Throwable
Usually derive from java.lang.Exception
The class name is the most important attribute of an exception
Can optionally include a message
Provide two constructors:
MyException( )
MyException(String s)
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
Throwing Exceptions, cont
Control is passed up the execution stack to a matching handler
Various methods exist for processing exceptions:
getMessage( )
toString( ) (class name + message)
printStackTrace( )
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
Throwing Exceptions, cont
Functions must “advertise” their exceptions
every function must specify the “checked” exceptions it (or its callees!) may throw
Callers must do one of two things:
handle your exceptions with try-catch, or
advertise your exceptions along with theirs
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
Sample Program
FixedStack
implements a stack with an array of Object
various methods throw exceptions
class StackException
StackTest
must handle StackExceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
class StackException extends Exception
{
StackException()
{}
StackException(String msg)
{
super(msg);
}
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
class FixedStack
{
private int capacity;
private int size;
private Object[] data;
public FixedStack(int cap)
{
data = new Object[cap];
capacity = cap;
size = 0;
}
public void push(Object o)
throws StackException
{
if (size == capacity)
throw new StackException("overflow");
data[size++] = o;
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
public Object pop()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[--size];
}
public Object top()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[size-1];
}
public int size()
{
return this.size;
}
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
class StackTest
{
public static void main(String[] args)
{
FixedStack s = new FixedStack(3);
doTest(s);
}
public static void doTest(FixedStack s)
{
try
{
System.out.println("Initial size = "
+ s.size());
s.push("one");
s.push(new Integer(2));
s.push(new Float(3.0));
s.push("one too many"); // error!
}
catch(StackException x)
{
System.out.println(x);
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
try
{
System.out.println("Top: " + s.top());
System.out.println("Popping...");
while (s.size() > 0)
System.out.println(s.pop());
}
catch(StackException x)
{
throw new InternalError(x.toString());
}
}
}
/* Output:
Initial size = 0
StackException: overflow
Top: 3.0
Popping...
3.0
2
one
*/
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
Using printStackTrace( )
catch(StackException x)
{
x.printStackTrace(System.out);
}
…
StackException: overflow
at FixedStack.push(FixedStack.java:18)
at StackTest.doTest(StackTest.java, Compiled Code)
at StackTest.main(StackTest.java:6)
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
Standard Java Exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Class java.lang.Exception
The one you usually derive from
“Checked Exceptions”
specifications checked at compile time
you must either catch or advertise these
Used for recoverable errors
Not programmer errors
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
java.lang.Exception Subclasses
AWTException
ClassNotFoundException
CloneNotSupportedException
IOException
NoSuchFieldException
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Class java.lang.Error
For JVM Failures and other Weird Things
let program terminate
InternalError is one of these
Don’t catch them
you don’t know what to do!
These are “unchecked exceptions”
not required to advertise
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
java.lang.Error Subclasses
AWTError
LinkageError
…
ThreadDeath
VirtualMachineError
InternalError, OutOfMemoryError, StackOverflowError, UnknownError
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
Class java.lang.RuntimeException
Stupid Name!
Same as logic_error in C++
Program logic errors
e.g., bad cast, using a null handle, array index violation, etc.
Shouldn’t happen!
fixed during testing
Similar in spirit to C’s assert( ) macro
mainly for debugging
These are called “unchecked exceptions”
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
java.lang.RuntimeException Subclasses (sample)
ArithmeticException (e.g., divide by 0)
ArrayStoreException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NullPointerException
UnsupportedOperationException
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
Principle
“Use checked exceptions for recoverable conditions and run-time exceptions for programming errors” (Bloch, Effective Java)
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
“Fixing” FixedStack
StackException should be a runtime exception
Then the “throws” specifications aren’t needed
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
class StackException extends RuntimeException
{
StackException()
{}
StackException(String msg)
{
super(msg);
}
}
Then remove all “throws” specifications from FixedStack
“Fixing” FixedStack
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
Exceptions and Inheritance
~ Subclass Overrides ~
Methods overridden in subclasses must maintain the parent method’s contract
substitutability
cannot add exceptions to specification
can omit, however
can throw subclasses of parent’s exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
// Relaxing the Exception Specification
class Parent
{
public void f() throws Exception
{}
}
class Child extends Parent
{
public void f() // OK!
{}
}
class Override
{
public static void main(String[] args)
{
Child c = new Child();
c.f();
}
}
Exceptions and Inheritance
~ Subclass Overrides ~
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
// Throwing a Subclass Exception
class MyException extends Exception {}
class AnotherException extends MyException {}
class Parent {
public void f() throws MyException
{}
}
class Child extends Parent {
public void f() throws AnotherException
{}
}
class Override {
public static void main(String[] args)
throws AnotherException
{
Child c = new Child();
c.f();
}
}
Exceptions and Inheritance
~ Subclass Overrides ~
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
Exception-handling Syntax
~ The Whole Picture ~
try
{
// normal code (conditionally executes)
}
catch (ExceptionType1 x)
{
// handle ExceptionType1 error
}
…
catch (ExceptionTypeN x)
{
// handle ExceptionTypeN error
}
finally
{
// invariant code ("always" executes)
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
The finally Clause
For code that must ALWAYS run
No matter what!
Even if a return or break occurs first
Exception: System.exit( )
Placed after handlers (if they exist)
try-block must either have a handler or a finally-block
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
class FinallyTest
{
public static void f()
throws Exception
{
try
{
// 0
// return; // 1
// System.exit(0); // 2
// throw new Exception(); // 3a
}
catch (Exception x)
{
// throw new Exception(); // 3b
}
finally
{
System.out.println("finally!");
}
System.out.println("last statement");
}
The finally Clause, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
public static void main(String[] args)
{
try
{
f();
}
catch(Exception x)
{}
}
}
The finally Clause, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
Program Output
0:
finally!
last statement
1:
finally!
2:
(no output)
3a:
same as 0:
3a + 3b:
compiler error (last statement not reachable)
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
Managing Resources
Other than memory
files, connections, etc.
Need to deallocate, even if exceptions occur
Use finally
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
import java.io.*;
class Manage
{
public static void f(String fname)
throws IOException
{
FileReader f = null; // must define outside try
try
{
f = new FileReader(fname);
System.out.println("File opened");
int c = f.read(); // read a byte
// ...
}
finally
{
if (f != null)
{
System.out.println("File closed");
f.close(); // beware lost exception!!!
}
}
}
Managing Resources
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
public static void main(String[] args)
{
try
{
f(args[0]);
}
catch (Exception x)
{
System.out.println(x);
}
}
}
Managing Resources
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Program Output
If no file name given (args.length == 0):
java.lang.ArrayIndexOutOfBoundsException: 0
If file doesn’t exist:
java.io.FileNotFoundException:
If file opened successfully:
file opened
file closed
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
When to Handle Exceptions
Note: Manage.f( ) didn’t catch anything
wouldn’t know what to do if it did!
You often let exceptions pass up the call stack
Or you can re-throw in a catch
throw x; // in a handler where x was caught
or re-throw a new type of exception
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Exception Etiquette
Don’t catch what you can’t (at least partially) handle
re-throw if only partially handled (“catch & release”: if you’re not going to eat it, throw it back!)
Don’t catch & ignore
catch (Exception x){} // disables exceptions!
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
How Exceptions Work
When an exception is thrown execution backtracks up the runtime stack (list of active function invocations)
Each stack frame contains information regarding local handlers, if any
Otherwise, execution returns up to the next caller, looking for a suitable catch
What happens if there isn’t a matching catch?
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
Uncaught Exceptions
What if there is no handler for an exception?
The thread dies!
exceptions belong to a thread (stack-specific)
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
Chapter 11: Multithreading
Multiple tasks for computer
Draw & display images on screen
Check keyboard & mouse input
Send & receive data on network
Read & write files to disk
Perform useful computation (editor, browser, game)
How does computer do everything at once?
Multitasking
Multiprocessing
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
Multitasking (Time-Sharing)
Approach
Computer does some work on a task
Computer then quickly switch to next task
Tasks managed by operating system (scheduler)
Computer seems to work on tasks concurrently
Can improve performance by reducing waiting
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
Multitasking Can Aid Performance
Single task
Two tasks
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
Multiprocessing (Multithreading)
Approach
Multiple processing units (multiprocessor)
Computer works on several tasks in parallel
Performance can be improved
4096 processor Cray X1
32 processor Pentium Xeon
Dual-core AMD Athlon X2
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Perform Multiple Tasks Using…
Process
Definition – executable program loaded in memory
Has own address space
Variables & data structures (in memory)
Each process may execute a different program
Communicate via operating system, files, network
May contain multiple threads
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Perform Multiple Tasks Using…
Thread
Definition – sequentially executed stream of instructions
Shares address space with other threads
Has own execution context
Program counter, call stack (local variables)
Communicate via shared access to data
Multiple threads in process execute same program
Also known as “lightweight process”
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
Web Server uses threads to handle …
Multiple simultaneous web browser requests
Motivation for Multithreading
Captures logical structure of problem
May have concurrent interacting components
Can handle each component using separate thread
Simplifies programming for problem
Example
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
Multiple simultaneous web browser requests…
Handled faster by multiple web servers
Motivation for Multithreading
Better utilize hardware resources
When a thread is delayed, compute other threads
Given extra hardware, compute threads in parallel
Reduce overall execution time
Example
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
Multithreading Overview
Motivation & background
Threads
Creating Java threads
Thread states
Scheduling
Synchronization
Data races
Locks
Wait / Notify
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
Programming with Threads
Concurrent programming
Writing programs divided into independent tasks
Tasks may be executed in parallel on multiprocessors
Multithreading
Executing program with multiple threads in parallel
Special form of multiprocessing
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
Creating Threads in Java
You have to specify the work you want the thread to do
Define a class that implements the Runnable interface
public interface Runnable {
public void run();
}
Put the work in the run method
Create an instance of the worker class and create a thread to run it
or hand the worker instance to an executor
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
Thread Class
public class Thread {
public Thread(Runnable R); // Thread R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
More Thread Class Methods
public class Thread {
…
public String getName();
public void interrupt();
public boolean isAlive();
public void join();
public void setDaemon(boolean on);
public void setName(String name);
public void setPriority(int level);
public static Thread currentThread();
public static void sleep(long milliseconds);
public static void yield();
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
Creating Threads in Java
Runnable interface
Create object implementing Runnable interface
Pass it to Thread object via Thread constructor
Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread t = new Thread(new MyT()); // create thread
t.start(); // begin running thread
… // thread executing in parallel
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Alternative (Not Recommended)
Directly extend Thread class
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT t = new MyT(); // create thread
t.start(); // begin running thread
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Why not recommended?
Not a big problem for getting started
but a bad habit for industrial strength development
The methods of the worker class and the Thread class get all tangled up
Makes it hard to migrate to Thread Pools and other more efficient approaches
11/20/2009
Võ Phương Bình - ITFAC - DLU
63
Threads – Thread States
Java thread can be in one of these states
New – thread allocated & waiting for start()
Runnable – thread can execute
Blocked – thread waiting for event (I/O, etc.)
Terminated – thread finished
Transitions between states caused by
Invoking methods in class Thread
start(), yield(), sleep()
Other (external) events
Scheduler, I/O, returning from run()…
11/20/2009
Võ Phương Bình - ITFAC - DLU
64
Threads – Thread States
State diagram
runnable
new
terminated
blocked
new
start
terminate
IO, sleep, join,
request lock
IO complete, sleep expired,
join complete,
acquire lock
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
Threads – Scheduling
Scheduler
Determines which runnable threads to run
Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Many computers can run multiple threads simultaneously (or nearly so)
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
Java Thread Example
public class ThreadExample implements Runnable {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
}
public static void main(String[] args) {
new Thread(new ThreadExample()).start();
new Thread( new ThreadExample()).start();
System.out.println("Done");
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Java Thread Example – Output
Possible outputs
0,1,2,0,1,2,Done // thread 1, thread 2, main()
0,1,2,Done,0,1,2 // thread 1, main(), thread 2
Done,0,1,2,0,1,2 // main(), thread 1, thread 2
0,0,1,1,2,Done,2 // main() & threads interleaved
thread 1: println 0, println 1, println 2
main (): thread 1, thread 2, println Done
thread 2: println 0, println 1, println 2
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
Might not see different interleavings
The threads in that example are too short
Each started thread will probably complete before the next thread starts
Let’s make more threads that run longer
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
Data Races
public class DataRace implements Runnable {
static volatile int x;
public void run() {
for (int i = 0; i < 10000; i++) {
x++;
x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x not always 0!
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Using Synchronization
public class DataRace implements Runnable {
static volatile int x;
static Object lock = new Object();
public void run() {
for (int i = 0; i < 10000; i++)
synchronized(lock) {
x++; x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x always 0!
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
71
Loading, Displaying and Scaling Images
Loading and Playing Audio Clips
Animating a Series of Images
Customizing Applets via the HTML param Tag
Chapter 12: Multimedia
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
Loading, Displaying and Scaling Images
Java Multimedia
Graphics, images, animations, sounds, and video
Begin with images
Class Image (java.awt)
Abstract class, cannot create an object directly
Must request that an Image be loaded and returned to you
Class Applet (superclass of JApplet) has this method
getImage( imageLocation, filename );
imageLocation - getDocumentBase() - URL (address) of HTML file
filename - Java supports .gif and .jpg (.jpeg)
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Loading, Displaying and Scaling Images (II)
Displaying Images with drawImage
Many overloaded versions
g.drawImage( myImage, x, y, ImageObserver );
myImage - Image object
x,y - coordinates to display image
ImageObserver - object on which image is displayed
Use "this" to indicate the applet
Can be any object that implements ImageObserver interface
g.drawImage( myImage, x, y, width, height, ImageObserver );
width and height - dimensions of image (automatically scaled)
getWidth(), getHeight() - return dimensions of applet
11/20/2009
Võ Phương Bình - ITFAC - DLU
74
Loading, Displaying and Scaling Images (III)
Class ImageIcon
Not an abstract class (can create objects)
Example constructor
private ImageIcon myIcon;
myIcon = new ImageIcon( "myIcon.gif" );
Displaying Icons with method paintIcon
myIcon.paintIcon( Component, Graphics, x, y )
Component - Component object on which to display image (this)
Graphics - Graphics object used to render image (g)
x, y - coordinates of Icon
11/20/2009
Võ Phương Bình - ITFAC - DLU
75
Loading, Displaying and Scaling Images (IV)
Usage
ImageIcons are simpler than Images
Create objects directly
No need for ImageObserver reference
However, cannot scale ImageIcons
Scaling
Use ImageIcon method getImage
Returns Image reference
This can be used with drawImage and be scaled
11/20/2009
Võ Phương Bình - ITFAC - DLU
76
Image Example
1. import
1.1 Declare objects
2. init()
2.1 Initialize objects
3. paint()
3.1 drawImage calls
11/20/2009
Võ Phương Bình - ITFAC - DLU
77
11/20/2009
Võ Phương Bình - ITFAC - DLU
78
Loading and Playing Audio Clips
Audio clips
Require speakers and a sound board
Sound engine - plays audio clips
Supports .au, .wav, .aif, .mid
Java Media Framework supports additional formats
Playing audio clips
play method in Applet
Plays clip once, marked for garbage collection when finished
play( location, soundFileName );
location - getDocumentBase (URL of HTML file)
play( soundURL );
soundURL - URL that contains location and filename of clip
11/20/2009
Võ Phương Bình - ITFAC - DLU
79
Loading and Playing Audio Clips (II)
Playing audio clips
Method play from AudioClip interface
More flexible than Applet method play
Audio stored in program, can be reused
getAudioClip
Returns reference to an AudioClip
Same format as Applet method play
getAudioClip( location, filename )
getAudioClip( soundURL )
Once AudioClip loaded, use methods
play - plays audio once
loop - continuous loops audio in background
stop - terminates clip that is currently playing
11/20/2009
Võ Phương Bình - ITFAC - DLU
80
1. import
1.1 Declare objects
2. init
2.1 Set layout
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
2.2 Add buttons
2.3 Initialize audio clips
3. stop
4. Class ButtonHandler
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
Animating a Series of Images
Following example
Use a series of images stored in an array
Use same techniques to load and display ImageIcons
Class Timer
Generates ActionEvents at a fixed interval in milliseconds
Timer ( animationDelay, ActionListener );
ActionListener - ActionListener that will respond to ActionEvents
Methods
start
stop
restart
isRunning
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
Animating a Series of Images (II)
Method repaint
Calls update, which calls paintComponent
Subclasses of JComponent should draw in method paintComponent
Call superclass`s paintComponent to make sure Swing components displayed properly
View area
Width and height specify entire window, not client area
Dimension objects
Contain width and height values
myDimObject = new Dimension( 100, 200 );
myDimObject.width
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
Animating a Series of Images (III)
getImageLoadStatus
ImageIcon method
Determines if image is completely loaded into memory
Only complete images should be displayed (smooth animation)
If loaded, returns MediaTracker.COMPLETE
MediaTracker
Can determine when images are loaded, or force program to wait if not
ImageIcon creates our MediaTracker for us
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
1. import
1.1 implements ActionListener
1.2 Declare objects
1.3 Constructor
1.4 Initialize ImageIcon array
2. paintComponent
2.1 Call to superclass paintComponent
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
2.2 If image loaded, display it (paintIcon)
2.3 Increment currentImage
3. actionPerformed
3.1 startAnimation
3.2 stopAnimation
3.3 getMinimumSize
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
3.4. getPreferredSize
4. main
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
Customizing Applets via the HTML param Tag
Applets
Customize through parameters in HTML file that invokes it
Invokes applet LogoApplet
param tags
Each has a name and a value
Use Applet method getParameter (returns a String)
parameter = getParameter( "animationdelay" );
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
In this chapter we will:
Read a File
Write a File
Chapter 13
Input and Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
File Input
11/20/2009
Võ Phương Bình - ITFAC - DLU
93
Example
Read File
public static void ReadFile(String filename)
{
FileReader fr;
try{
fr = new FileReader(filename);
char str[]={2};
try{
while(fr.read(str)!=-1)
{
System.out.print(str);
}
}
catch(IOException ioe)
{}
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
94
File Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
95
Example
Write to File
public static void WriteFile(String filename, String str)
{
FileWriter fw;
try{
fw = new FileWriter(filename, true);
fw.write(str);
fw.close();
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
96
Introduction to Networking
Java Network Programming
Chapter 14: Networking
11/20/2009
Võ Phương Bình - ITFAC - DLU
97
Java supports stream sockets and datagram sockets
Datagram socket
- individual packets of information are transmitted
- Connection-less service
- The protocol for transmission is UDP
Stream socket:
- Data flows between the processes while the connection is in place
- Connection-oriented
- The protocol for transmission is TCP
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
98
Networking with Java
Uses for TCP Sockets
- Network overhead is not important
- Reliable transfer in required
Uses for UDP Sockets
- Network overhead must be minimized
- Data reliability is not crucial
- small independent applications packets needed
11/20/2009
Võ Phương Bình - ITFAC - DLU
99
Relevant Classes for network programming with Java
Socket - a TCP connection socket
ServerSocket - a TCP server socket
DatagramPacket - a UDP packet
DatagramSocket - a UDP socket
InetAddress - an internet address
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
100
Networking with Java
Client/Server Model
Provides a service: ftp, www, telnet, etc
Clients
11/20/2009
Võ Phương Bình - ITFAC - DLU
101
Establishing a Simple Server (TCP)
This specifies the port and
specifies the maximum
number of clients that
connect to the server
Listens indefinitely for
an attempt by a client to
connect.
Once the connection is
established, get the Streams
that will allow the client
and server to communicate
The client and server
send each other data, via
the Streams
When the transmission is
complete, the server closes
the connection
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
102
Create a server that listens on port 8000. The client will send Strings. Display the Strings in the TextArea
11/20/2009
Võ Phương Bình - ITFAC - DLU
103
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class SimpleServer extends JFrame {
JTextArea display;
public SimpleServer( ) {
super(“Simple Server”);
Container con = getContentPane( );
display = new JTextArea(10,30);
display.setEditable(false);
con.add(display);
setSize(400,300);
setVisible(true);
}
public void startServer( ) {
ServerSocket server=null;
Socket connection=null;
String message;
DataInputStream input;
try {
server = new ServerSocket (8000);
while( true) {
connection = server.accept ();
display.append("Connection established ");
input = new DataInputStream (connection.getInputStream () );
message = input.readUTF();
display.append("Received message: "+message+" ");
connection.close();
}
} catch (IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
104
public static void main(String args[] ) {
SimpleServer s = new SimpleServer( );
s.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
s.startServer();
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
105
Establishing a Simple Client (TCP)
Networking with Java
Create a Socket to connect
to the server
Get the OutputStream and InputStream of the Socket
Close the connection
Communicate with the server
This specifies the server’s
Internet address and the
port number for the Socket
Get the Streams
that will allow the client
and server to communicate
The client and server
send each other data, via
the Streams
When the transmission is
complete, close
the connection
11/20/2009
Võ Phương Bình - ITFAC - DLU
106
Create a client that sends data to the Simple Server. The user types text in the TextField and then presses the Send Button. The text in the TextField is sent to the Server. The Server is listening on port 8000.
11/20/2009
Võ Phương Bình - ITFAC - DLU
107
import java.awt.*;
import java.net.*;
import java.awt.event.*;
javax.swing.*
import java.io.*;
public class SimpleClient extends JFrame implements ActionListener{
JTextField sendThis;
JButton send;
public SimpleClient( ) {
super("Simple Client");
Container con = getContentPane( );
con.setLayout(new FlowLayout( ) );
sendThis = new JTextField(15);
con.add(sendThis);
send = new JButton("Send");
send.addActionListener(this);
con.add(send);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent action) {
Socket client = null;
DataOutputStream output;
try {
// client = new Socket( InetAddress.getByName("kneedeep.cis.famu.edu"),8000);
client = new Socket( InetAddress.getLocalHost(),8000);
output = new DataOutputStream( client.getOutputStream( ) );
output.writeUTF( sendThis.getText( ) );
} catch(IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
108
public static void main(String args[ ] ) {
SimpleClient c = new SimpleClient();
c.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
109
Create a server that returns the current Date to a client. Create the client that requests the current Date.
11/20/2009
Võ Phương Bình - ITFAC - DLU
110
Create a server that returns the current Date to a client. Create the client that requests the current Date.
11/20/2009
Võ Phương Bình - ITFAC - DLU
111
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class DateClient extends JFrame implements ActionListener{
JTextField theDate;
JButton getDate;
public DateClient( ) {
super("Date Client");
Container con = getContentPane( );
con.setLayout( new FlowLayout( ) );
theDate = new JTextField(15);
con.add(theDate);
getDate = new JButton("What is the date?");
getDate.addActionListener(this);
con.add(getDate);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent action) {
String date;
Socket client = null;
DataOutputStream output;
DataInputStream input;
try {
// client = new Socket( InetAddress.getByName("kneedeep.cis.famu.edu"),8000);
client = new Socket( InetAddress.getLocalHost(),8000);
output = new DataOutputStream( client.getOutputStream() );
output.writeUTF("Give me the date");
input = new DataInputStream( client.getInputStream() );
date = input.readUTF( );
theDate.setText( date );
} catch(IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
112
public static void main(String args[ ] ) {
DateClient c = new DateClient();
c.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
}
The Server is next . . .
11/20/2009
Võ Phương Bình - ITFAC - DLU
113
import java.net.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
public class DateServer extends JFrame {
JTextArea display;
public DateServer( ) {
super("Date Server");
Container con = getContentPane( );
display = new JTextArea(10,45);
display.setEditable(false);
con.add(display);
setSize(400,300);
setVisible(true);
}
public void startServer( ) {
ServerSocket server=null;
Socket connection=null;
String message;
DataInputStream input;
DataOutputStream output;
try {
server = new ServerSocket (8000);
while( true) {
connection = server.accept ();
display.append("Connection established ");
input = new DataInputStream (connection.getInputStream () );
output = new DataOutputStream (connection.getOutputStream ( ) );
11/20/2009
Võ Phương Bình - ITFAC - DLU
114
message = input.readUTF();
if( message.equals("Give me the date") ) {
display.append("Client wants the date ");
String dateString = DateFormat.getDateInstance().format( new Date() );
output.writeUTF( dateString );
}
connection.close();
}
} catch (IOException e) { e.printStackTrace(); }
}
public static void main(String args[] ) {
DateServer s = new DateServer( );
s.startServer();
}
}
Võ Phương Bình - ITFAC - DLU
1
Part IV: Developing Comprehensive Projects
Chapter 10: Exception Handling
Chapter 11: Multithreading
Chapter 12: Multimedia
Chapter 13: Input and Output
Chapter 14: Networking
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 10
Exception Handling
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
Exceptions and Polymorphism
The finally clause
Resource Management
Uncaught Exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
What Exceptions are For
To handle Bad Things
I/O errors, other runtime errors
when a function fails to fulfill its specification
so you can restore program stability (or exit gracefully)
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
What Exceptions are For, cont
To force you to handle Bad Things
because return codes can be tedious
and sometimes you’re lazy
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
Example File I/O
public FileReader(String fileName)
throws FileNotFoundException
public void close() throws IOException
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
import java.io.*;
class OpenFile
{
public static void main(String[] args)
{
if (args.length > 0)
{
try
{
// Open a file:
FileReader f =
new FileReader(args[0]);
System.out.println(args[0]
+ " opened");
f.close();
}
catch (IOException x)
{
System.out.println(x);
}
}
}
}
Example File I/O, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
What Exceptions are For, cont
To signal errors from constructors
because constructors have no return value
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
What Exceptions are NOT For
NOT For Alternate Returns:
e.g., when end-of-file is reached:
while ((s = f.readLine()) != null) …
Exceptions are only for the exceptional!
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Catching Exceptions
Wrap code to be checked in a try-block
checking occurs all the way down the execution stack
try-blocks can be nested
control resumes at most enclosed matching handler
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Catching Exceptions, cont
Place one or more catch-clauses after try-block
runtime system looks back up the call stack for a matching handler
subclass types match superclass types
catching Exception catches everything (almost)
handlers are checked in the order they appear
place most derived types first!
execution resumes after last handler
if you let it (could branch or throw)
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
Throwing Exceptions
Must throw objects derived (ultimately) from Throwable
Usually derive from java.lang.Exception
The class name is the most important attribute of an exception
Can optionally include a message
Provide two constructors:
MyException( )
MyException(String s)
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
Throwing Exceptions, cont
Control is passed up the execution stack to a matching handler
Various methods exist for processing exceptions:
getMessage( )
toString( ) (class name + message)
printStackTrace( )
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
Throwing Exceptions, cont
Functions must “advertise” their exceptions
every function must specify the “checked” exceptions it (or its callees!) may throw
Callers must do one of two things:
handle your exceptions with try-catch, or
advertise your exceptions along with theirs
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
Sample Program
FixedStack
implements a stack with an array of Object
various methods throw exceptions
class StackException
StackTest
must handle StackExceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
class StackException extends Exception
{
StackException()
{}
StackException(String msg)
{
super(msg);
}
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
class FixedStack
{
private int capacity;
private int size;
private Object[] data;
public FixedStack(int cap)
{
data = new Object[cap];
capacity = cap;
size = 0;
}
public void push(Object o)
throws StackException
{
if (size == capacity)
throw new StackException("overflow");
data[size++] = o;
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
public Object pop()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[--size];
}
public Object top()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[size-1];
}
public int size()
{
return this.size;
}
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
class StackTest
{
public static void main(String[] args)
{
FixedStack s = new FixedStack(3);
doTest(s);
}
public static void doTest(FixedStack s)
{
try
{
System.out.println("Initial size = "
+ s.size());
s.push("one");
s.push(new Integer(2));
s.push(new Float(3.0));
s.push("one too many"); // error!
}
catch(StackException x)
{
System.out.println(x);
}
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
try
{
System.out.println("Top: " + s.top());
System.out.println("Popping...");
while (s.size() > 0)
System.out.println(s.pop());
}
catch(StackException x)
{
throw new InternalError(x.toString());
}
}
}
/* Output:
Initial size = 0
StackException: overflow
Top: 3.0
Popping...
3.0
2
one
*/
Sample Program, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
Using printStackTrace( )
catch(StackException x)
{
x.printStackTrace(System.out);
}
…
StackException: overflow
at FixedStack.push(FixedStack.java:18)
at StackTest.doTest(StackTest.java, Compiled Code)
at StackTest.main(StackTest.java:6)
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
Standard Java Exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Class java.lang.Exception
The one you usually derive from
“Checked Exceptions”
specifications checked at compile time
you must either catch or advertise these
Used for recoverable errors
Not programmer errors
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
java.lang.Exception Subclasses
AWTException
ClassNotFoundException
CloneNotSupportedException
IOException
NoSuchFieldException
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Class java.lang.Error
For JVM Failures and other Weird Things
let program terminate
InternalError is one of these
Don’t catch them
you don’t know what to do!
These are “unchecked exceptions”
not required to advertise
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
java.lang.Error Subclasses
AWTError
LinkageError
…
ThreadDeath
VirtualMachineError
InternalError, OutOfMemoryError, StackOverflowError, UnknownError
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
Class java.lang.RuntimeException
Stupid Name!
Same as logic_error in C++
Program logic errors
e.g., bad cast, using a null handle, array index violation, etc.
Shouldn’t happen!
fixed during testing
Similar in spirit to C’s assert( ) macro
mainly for debugging
These are called “unchecked exceptions”
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
java.lang.RuntimeException Subclasses (sample)
ArithmeticException (e.g., divide by 0)
ArrayStoreException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NullPointerException
UnsupportedOperationException
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
Principle
“Use checked exceptions for recoverable conditions and run-time exceptions for programming errors” (Bloch, Effective Java)
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
“Fixing” FixedStack
StackException should be a runtime exception
Then the “throws” specifications aren’t needed
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
class StackException extends RuntimeException
{
StackException()
{}
StackException(String msg)
{
super(msg);
}
}
Then remove all “throws” specifications from FixedStack
“Fixing” FixedStack
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
Exceptions and Inheritance
~ Subclass Overrides ~
Methods overridden in subclasses must maintain the parent method’s contract
substitutability
cannot add exceptions to specification
can omit, however
can throw subclasses of parent’s exceptions
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
// Relaxing the Exception Specification
class Parent
{
public void f() throws Exception
{}
}
class Child extends Parent
{
public void f() // OK!
{}
}
class Override
{
public static void main(String[] args)
{
Child c = new Child();
c.f();
}
}
Exceptions and Inheritance
~ Subclass Overrides ~
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
// Throwing a Subclass Exception
class MyException extends Exception {}
class AnotherException extends MyException {}
class Parent {
public void f() throws MyException
{}
}
class Child extends Parent {
public void f() throws AnotherException
{}
}
class Override {
public static void main(String[] args)
throws AnotherException
{
Child c = new Child();
c.f();
}
}
Exceptions and Inheritance
~ Subclass Overrides ~
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
Exception-handling Syntax
~ The Whole Picture ~
try
{
// normal code (conditionally executes)
}
catch (ExceptionType1 x)
{
// handle ExceptionType1 error
}
…
catch (ExceptionTypeN x)
{
// handle ExceptionTypeN error
}
finally
{
// invariant code ("always" executes)
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
The finally Clause
For code that must ALWAYS run
No matter what!
Even if a return or break occurs first
Exception: System.exit( )
Placed after handlers (if they exist)
try-block must either have a handler or a finally-block
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
class FinallyTest
{
public static void f()
throws Exception
{
try
{
// 0
// return; // 1
// System.exit(0); // 2
// throw new Exception(); // 3a
}
catch (Exception x)
{
// throw new Exception(); // 3b
}
finally
{
System.out.println("finally!");
}
System.out.println("last statement");
}
The finally Clause, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
public static void main(String[] args)
{
try
{
f();
}
catch(Exception x)
{}
}
}
The finally Clause, cont
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
Program Output
0:
finally!
last statement
1:
finally!
2:
(no output)
3a:
same as 0:
3a + 3b:
compiler error (last statement not reachable)
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
Managing Resources
Other than memory
files, connections, etc.
Need to deallocate, even if exceptions occur
Use finally
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
import java.io.*;
class Manage
{
public static void f(String fname)
throws IOException
{
FileReader f = null; // must define outside try
try
{
f = new FileReader(fname);
System.out.println("File opened");
int c = f.read(); // read a byte
// ...
}
finally
{
if (f != null)
{
System.out.println("File closed");
f.close(); // beware lost exception!!!
}
}
}
Managing Resources
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
public static void main(String[] args)
{
try
{
f(args[0]);
}
catch (Exception x)
{
System.out.println(x);
}
}
}
Managing Resources
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Program Output
If no file name given (args.length == 0):
java.lang.ArrayIndexOutOfBoundsException: 0
If file doesn’t exist:
java.io.FileNotFoundException:
If file opened successfully:
file opened
file closed
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
When to Handle Exceptions
Note: Manage.f( ) didn’t catch anything
wouldn’t know what to do if it did!
You often let exceptions pass up the call stack
Or you can re-throw in a catch
throw x; // in a handler where x was caught
or re-throw a new type of exception
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Exception Etiquette
Don’t catch what you can’t (at least partially) handle
re-throw if only partially handled (“catch & release”: if you’re not going to eat it, throw it back!)
Don’t catch & ignore
catch (Exception x){} // disables exceptions!
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
How Exceptions Work
When an exception is thrown execution backtracks up the runtime stack (list of active function invocations)
Each stack frame contains information regarding local handlers, if any
Otherwise, execution returns up to the next caller, looking for a suitable catch
What happens if there isn’t a matching catch?
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
Uncaught Exceptions
What if there is no handler for an exception?
The thread dies!
exceptions belong to a thread (stack-specific)
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
Chapter 11: Multithreading
Multiple tasks for computer
Draw & display images on screen
Check keyboard & mouse input
Send & receive data on network
Read & write files to disk
Perform useful computation (editor, browser, game)
How does computer do everything at once?
Multitasking
Multiprocessing
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
Multitasking (Time-Sharing)
Approach
Computer does some work on a task
Computer then quickly switch to next task
Tasks managed by operating system (scheduler)
Computer seems to work on tasks concurrently
Can improve performance by reducing waiting
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
Multitasking Can Aid Performance
Single task
Two tasks
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
Multiprocessing (Multithreading)
Approach
Multiple processing units (multiprocessor)
Computer works on several tasks in parallel
Performance can be improved
4096 processor Cray X1
32 processor Pentium Xeon
Dual-core AMD Athlon X2
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Perform Multiple Tasks Using…
Process
Definition – executable program loaded in memory
Has own address space
Variables & data structures (in memory)
Each process may execute a different program
Communicate via operating system, files, network
May contain multiple threads
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Perform Multiple Tasks Using…
Thread
Definition – sequentially executed stream of instructions
Shares address space with other threads
Has own execution context
Program counter, call stack (local variables)
Communicate via shared access to data
Multiple threads in process execute same program
Also known as “lightweight process”
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
Web Server uses threads to handle …
Multiple simultaneous web browser requests
Motivation for Multithreading
Captures logical structure of problem
May have concurrent interacting components
Can handle each component using separate thread
Simplifies programming for problem
Example
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
Multiple simultaneous web browser requests…
Handled faster by multiple web servers
Motivation for Multithreading
Better utilize hardware resources
When a thread is delayed, compute other threads
Given extra hardware, compute threads in parallel
Reduce overall execution time
Example
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
Multithreading Overview
Motivation & background
Threads
Creating Java threads
Thread states
Scheduling
Synchronization
Data races
Locks
Wait / Notify
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
Programming with Threads
Concurrent programming
Writing programs divided into independent tasks
Tasks may be executed in parallel on multiprocessors
Multithreading
Executing program with multiple threads in parallel
Special form of multiprocessing
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
Creating Threads in Java
You have to specify the work you want the thread to do
Define a class that implements the Runnable interface
public interface Runnable {
public void run();
}
Put the work in the run method
Create an instance of the worker class and create a thread to run it
or hand the worker instance to an executor
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
Thread Class
public class Thread {
public Thread(Runnable R); // Thread R.run()
public Thread(Runnable R, String name);
public void start(); // begin thread execution
...
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
More Thread Class Methods
public class Thread {
…
public String getName();
public void interrupt();
public boolean isAlive();
public void join();
public void setDaemon(boolean on);
public void setName(String name);
public void setPriority(int level);
public static Thread currentThread();
public static void sleep(long milliseconds);
public static void yield();
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
Creating Threads in Java
Runnable interface
Create object implementing Runnable interface
Pass it to Thread object via Thread constructor
Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread t = new Thread(new MyT()); // create thread
t.start(); // begin running thread
… // thread executing in parallel
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Alternative (Not Recommended)
Directly extend Thread class
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT t = new MyT(); // create thread
t.start(); // begin running thread
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Why not recommended?
Not a big problem for getting started
but a bad habit for industrial strength development
The methods of the worker class and the Thread class get all tangled up
Makes it hard to migrate to Thread Pools and other more efficient approaches
11/20/2009
Võ Phương Bình - ITFAC - DLU
63
Threads – Thread States
Java thread can be in one of these states
New – thread allocated & waiting for start()
Runnable – thread can execute
Blocked – thread waiting for event (I/O, etc.)
Terminated – thread finished
Transitions between states caused by
Invoking methods in class Thread
start(), yield(), sleep()
Other (external) events
Scheduler, I/O, returning from run()…
11/20/2009
Võ Phương Bình - ITFAC - DLU
64
Threads – Thread States
State diagram
runnable
new
terminated
blocked
new
start
terminate
IO, sleep, join,
request lock
IO complete, sleep expired,
join complete,
acquire lock
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
Threads – Scheduling
Scheduler
Determines which runnable threads to run
Can be based on thread priority
Part of OS or Java Virtual Machine (JVM)
Many computers can run multiple threads simultaneously (or nearly so)
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
Java Thread Example
public class ThreadExample implements Runnable {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
}
public static void main(String[] args) {
new Thread(new ThreadExample()).start();
new Thread( new ThreadExample()).start();
System.out.println("Done");
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Java Thread Example – Output
Possible outputs
0,1,2,0,1,2,Done // thread 1, thread 2, main()
0,1,2,Done,0,1,2 // thread 1, main(), thread 2
Done,0,1,2,0,1,2 // main(), thread 1, thread 2
0,0,1,1,2,Done,2 // main() & threads interleaved
thread 1: println 0, println 1, println 2
main (): thread 1, thread 2, println Done
thread 2: println 0, println 1, println 2
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
Might not see different interleavings
The threads in that example are too short
Each started thread will probably complete before the next thread starts
Let’s make more threads that run longer
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
Data Races
public class DataRace implements Runnable {
static volatile int x;
public void run() {
for (int i = 0; i < 10000; i++) {
x++;
x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x not always 0!
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Using Synchronization
public class DataRace implements Runnable {
static volatile int x;
static Object lock = new Object();
public void run() {
for (int i = 0; i < 10000; i++)
synchronized(lock) {
x++; x--;
}
}
public static void main(String[] args) throws Exception {
Thread [] threads = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(new DataRace());
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println(x); // x always 0!
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
71
Loading, Displaying and Scaling Images
Loading and Playing Audio Clips
Animating a Series of Images
Customizing Applets via the HTML param Tag
Chapter 12: Multimedia
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
Loading, Displaying and Scaling Images
Java Multimedia
Graphics, images, animations, sounds, and video
Begin with images
Class Image (java.awt)
Abstract class, cannot create an object directly
Must request that an Image be loaded and returned to you
Class Applet (superclass of JApplet) has this method
getImage( imageLocation, filename );
imageLocation - getDocumentBase() - URL (address) of HTML file
filename - Java supports .gif and .jpg (.jpeg)
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Loading, Displaying and Scaling Images (II)
Displaying Images with drawImage
Many overloaded versions
g.drawImage( myImage, x, y, ImageObserver );
myImage - Image object
x,y - coordinates to display image
ImageObserver - object on which image is displayed
Use "this" to indicate the applet
Can be any object that implements ImageObserver interface
g.drawImage( myImage, x, y, width, height, ImageObserver );
width and height - dimensions of image (automatically scaled)
getWidth(), getHeight() - return dimensions of applet
11/20/2009
Võ Phương Bình - ITFAC - DLU
74
Loading, Displaying and Scaling Images (III)
Class ImageIcon
Not an abstract class (can create objects)
Example constructor
private ImageIcon myIcon;
myIcon = new ImageIcon( "myIcon.gif" );
Displaying Icons with method paintIcon
myIcon.paintIcon( Component, Graphics, x, y )
Component - Component object on which to display image (this)
Graphics - Graphics object used to render image (g)
x, y - coordinates of Icon
11/20/2009
Võ Phương Bình - ITFAC - DLU
75
Loading, Displaying and Scaling Images (IV)
Usage
ImageIcons are simpler than Images
Create objects directly
No need for ImageObserver reference
However, cannot scale ImageIcons
Scaling
Use ImageIcon method getImage
Returns Image reference
This can be used with drawImage and be scaled
11/20/2009
Võ Phương Bình - ITFAC - DLU
76
Image Example
1. import
1.1 Declare objects
2. init()
2.1 Initialize objects
3. paint()
3.1 drawImage calls
11/20/2009
Võ Phương Bình - ITFAC - DLU
77
11/20/2009
Võ Phương Bình - ITFAC - DLU
78
Loading and Playing Audio Clips
Audio clips
Require speakers and a sound board
Sound engine - plays audio clips
Supports .au, .wav, .aif, .mid
Java Media Framework supports additional formats
Playing audio clips
play method in Applet
Plays clip once, marked for garbage collection when finished
play( location, soundFileName );
location - getDocumentBase (URL of HTML file)
play( soundURL );
soundURL - URL that contains location and filename of clip
11/20/2009
Võ Phương Bình - ITFAC - DLU
79
Loading and Playing Audio Clips (II)
Playing audio clips
Method play from AudioClip interface
More flexible than Applet method play
Audio stored in program, can be reused
getAudioClip
Returns reference to an AudioClip
Same format as Applet method play
getAudioClip( location, filename )
getAudioClip( soundURL )
Once AudioClip loaded, use methods
play - plays audio once
loop - continuous loops audio in background
stop - terminates clip that is currently playing
11/20/2009
Võ Phương Bình - ITFAC - DLU
80
1. import
1.1 Declare objects
2. init
2.1 Set layout
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
2.2 Add buttons
2.3 Initialize audio clips
3. stop
4. Class ButtonHandler
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
Animating a Series of Images
Following example
Use a series of images stored in an array
Use same techniques to load and display ImageIcons
Class Timer
Generates ActionEvents at a fixed interval in milliseconds
Timer ( animationDelay, ActionListener );
ActionListener - ActionListener that will respond to ActionEvents
Methods
start
stop
restart
isRunning
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
Animating a Series of Images (II)
Method repaint
Calls update, which calls paintComponent
Subclasses of JComponent should draw in method paintComponent
Call superclass`s paintComponent to make sure Swing components displayed properly
View area
Width and height specify entire window, not client area
Dimension objects
Contain width and height values
myDimObject = new Dimension( 100, 200 );
myDimObject.width
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
Animating a Series of Images (III)
getImageLoadStatus
ImageIcon method
Determines if image is completely loaded into memory
Only complete images should be displayed (smooth animation)
If loaded, returns MediaTracker.COMPLETE
MediaTracker
Can determine when images are loaded, or force program to wait if not
ImageIcon creates our MediaTracker for us
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
1. import
1.1 implements ActionListener
1.2 Declare objects
1.3 Constructor
1.4 Initialize ImageIcon array
2. paintComponent
2.1 Call to superclass paintComponent
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
2.2 If image loaded, display it (paintIcon)
2.3 Increment currentImage
3. actionPerformed
3.1 startAnimation
3.2 stopAnimation
3.3 getMinimumSize
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
3.4. getPreferredSize
4. main
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
Customizing Applets via the HTML param Tag
Applets
Customize through parameters in HTML file that invokes it
Invokes applet LogoApplet
param tags
Each has a name and a value
Use Applet method getParameter (returns a String)
parameter = getParameter( "animationdelay" );
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
In this chapter we will:
Read a File
Write a File
Chapter 13
Input and Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
File Input
11/20/2009
Võ Phương Bình - ITFAC - DLU
93
Example
Read File
public static void ReadFile(String filename)
{
FileReader fr;
try{
fr = new FileReader(filename);
char str[]={2};
try{
while(fr.read(str)!=-1)
{
System.out.print(str);
}
}
catch(IOException ioe)
{}
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
94
File Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
95
Example
Write to File
public static void WriteFile(String filename, String str)
{
FileWriter fw;
try{
fw = new FileWriter(filename, true);
fw.write(str);
fw.close();
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
96
Introduction to Networking
Java Network Programming
Chapter 14: Networking
11/20/2009
Võ Phương Bình - ITFAC - DLU
97
Java supports stream sockets and datagram sockets
Datagram socket
- individual packets of information are transmitted
- Connection-less service
- The protocol for transmission is UDP
Stream socket:
- Data flows between the processes while the connection is in place
- Connection-oriented
- The protocol for transmission is TCP
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
98
Networking with Java
Uses for TCP Sockets
- Network overhead is not important
- Reliable transfer in required
Uses for UDP Sockets
- Network overhead must be minimized
- Data reliability is not crucial
- small independent applications packets needed
11/20/2009
Võ Phương Bình - ITFAC - DLU
99
Relevant Classes for network programming with Java
Socket - a TCP connection socket
ServerSocket - a TCP server socket
DatagramPacket - a UDP packet
DatagramSocket - a UDP socket
InetAddress - an internet address
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
100
Networking with Java
Client/Server Model
Provides a service: ftp, www, telnet, etc
Clients
11/20/2009
Võ Phương Bình - ITFAC - DLU
101
Establishing a Simple Server (TCP)
This specifies the port and
specifies the maximum
number of clients that
connect to the server
Listens indefinitely for
an attempt by a client to
connect.
Once the connection is
established, get the Streams
that will allow the client
and server to communicate
The client and server
send each other data, via
the Streams
When the transmission is
complete, the server closes
the connection
Networking with Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
102
Create a server that listens on port 8000. The client will send Strings. Display the Strings in the TextArea
11/20/2009
Võ Phương Bình - ITFAC - DLU
103
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class SimpleServer extends JFrame {
JTextArea display;
public SimpleServer( ) {
super(“Simple Server”);
Container con = getContentPane( );
display = new JTextArea(10,30);
display.setEditable(false);
con.add(display);
setSize(400,300);
setVisible(true);
}
public void startServer( ) {
ServerSocket server=null;
Socket connection=null;
String message;
DataInputStream input;
try {
server = new ServerSocket (8000);
while( true) {
connection = server.accept ();
display.append("Connection established ");
input = new DataInputStream (connection.getInputStream () );
message = input.readUTF();
display.append("Received message: "+message+" ");
connection.close();
}
} catch (IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
104
public static void main(String args[] ) {
SimpleServer s = new SimpleServer( );
s.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
s.startServer();
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
105
Establishing a Simple Client (TCP)
Networking with Java
Create a Socket to connect
to the server
Get the OutputStream and InputStream of the Socket
Close the connection
Communicate with the server
This specifies the server’s
Internet address and the
port number for the Socket
Get the Streams
that will allow the client
and server to communicate
The client and server
send each other data, via
the Streams
When the transmission is
complete, close
the connection
11/20/2009
Võ Phương Bình - ITFAC - DLU
106
Create a client that sends data to the Simple Server. The user types text in the TextField and then presses the Send Button. The text in the TextField is sent to the Server. The Server is listening on port 8000.
11/20/2009
Võ Phương Bình - ITFAC - DLU
107
import java.awt.*;
import java.net.*;
import java.awt.event.*;
javax.swing.*
import java.io.*;
public class SimpleClient extends JFrame implements ActionListener{
JTextField sendThis;
JButton send;
public SimpleClient( ) {
super("Simple Client");
Container con = getContentPane( );
con.setLayout(new FlowLayout( ) );
sendThis = new JTextField(15);
con.add(sendThis);
send = new JButton("Send");
send.addActionListener(this);
con.add(send);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent action) {
Socket client = null;
DataOutputStream output;
try {
// client = new Socket( InetAddress.getByName("kneedeep.cis.famu.edu"),8000);
client = new Socket( InetAddress.getLocalHost(),8000);
output = new DataOutputStream( client.getOutputStream( ) );
output.writeUTF( sendThis.getText( ) );
} catch(IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
108
public static void main(String args[ ] ) {
SimpleClient c = new SimpleClient();
c.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
109
Create a server that returns the current Date to a client. Create the client that requests the current Date.
11/20/2009
Võ Phương Bình - ITFAC - DLU
110
Create a server that returns the current Date to a client. Create the client that requests the current Date.
11/20/2009
Võ Phương Bình - ITFAC - DLU
111
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class DateClient extends JFrame implements ActionListener{
JTextField theDate;
JButton getDate;
public DateClient( ) {
super("Date Client");
Container con = getContentPane( );
con.setLayout( new FlowLayout( ) );
theDate = new JTextField(15);
con.add(theDate);
getDate = new JButton("What is the date?");
getDate.addActionListener(this);
con.add(getDate);
setSize(200,300);
setVisible(true);
}
public void actionPerformed(ActionEvent action) {
String date;
Socket client = null;
DataOutputStream output;
DataInputStream input;
try {
// client = new Socket( InetAddress.getByName("kneedeep.cis.famu.edu"),8000);
client = new Socket( InetAddress.getLocalHost(),8000);
output = new DataOutputStream( client.getOutputStream() );
output.writeUTF("Give me the date");
input = new DataInputStream( client.getInputStream() );
date = input.readUTF( );
theDate.setText( date );
} catch(IOException e) { e.printStackTrace(); }
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
112
public static void main(String args[ ] ) {
DateClient c = new DateClient();
c.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
}
The Server is next . . .
11/20/2009
Võ Phương Bình - ITFAC - DLU
113
import java.net.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
public class DateServer extends JFrame {
JTextArea display;
public DateServer( ) {
super("Date Server");
Container con = getContentPane( );
display = new JTextArea(10,45);
display.setEditable(false);
con.add(display);
setSize(400,300);
setVisible(true);
}
public void startServer( ) {
ServerSocket server=null;
Socket connection=null;
String message;
DataInputStream input;
DataOutputStream output;
try {
server = new ServerSocket (8000);
while( true) {
connection = server.accept ();
display.append("Connection established ");
input = new DataInputStream (connection.getInputStream () );
output = new DataOutputStream (connection.getOutputStream ( ) );
11/20/2009
Võ Phương Bình - ITFAC - DLU
114
message = input.readUTF();
if( message.equals("Give me the date") ) {
display.append("Client wants the date ");
String dateString = DateFormat.getDateInstance().format( new Date() );
output.writeUTF( dateString );
}
connection.close();
}
} catch (IOException e) { e.printStackTrace(); }
}
public static void main(String args[] ) {
DateServer s = new DateServer( );
s.startServer();
}
}
* Một số tài liệu cũ có thể bị lỗi font khi hiển thị do dùng bộ mã không phải Unikey ...
Người chia sẻ: Nguyễn Bùi Minh Tâm
Dung lượng: |
Lượt tài: 0
Loại file:
Nguồn : Chưa rõ
(Tài liệu chưa được thẩm định)