Transcript CS 21b

Threads
CS 21b
Threads in Java
Definition
unit of program control that represents an
execution sequence
Java supports multi-threaded execution
* Programs we have written up to this point
have been on a single thread of control
The Thread class
Thread creation
instantiate a class that extends Thread
instantiate the class Thread but provide a
run() method
Thread execution
let t refer to a thread object
t.start() causes the thread to execute its
run() method “in the background”
Example 1: PrintThread
PrintThread class extends Thread
Attributes: name & timedelay
Constructor sets name and timedelay
run method prints name twice but with a
time delay in between the print
statements
use Thread method sleep(timedelay)
run() Method
for PrintThread
public class PrintThread extends Thread {
...
public void run() {
System.out.println(name);
try { sleep(timedelay); }
catch(Exception e) {}
System.out.println(name);
}
…
}
Using PrintThread
PrintThread t1,t2,t3;
t1 = new PrintThread("tic",5000);
t2 = new PrintThread("tac",1000);
t3 = new PrintThread("toe",3000);
t1.start();
t2.start();
t3.start();
// expected output ? last output line should be tic
Example 2: MovingCircle
MovingCircle class extends Applet
Attributes: xpos & size (of circle)
provide initial values
paint() method: draws the circle
Thread created inside init()
run() method has a loop that continuously
updates xpos & size and then repaints
A button executes the thread (t.start())
MovingCircle class
(attributes & paint())
// sample animation using Threads
public class MovingCircle extends Applet {
int xpos = 5; // these variables will be updated
int size = 10; // on a different thread
...
public void paint(Graphics g) {
g.drawOval(xpos,50,size,size);
}
…
}
MovingCircle class
(thread code)
t = new Thread() {
public void run() {
while (xpos < 80) {
try {sleep(1000);} catch(Exception e) {}
xpos +=5;
size += 3;
repaint(); // forces paint() to be re-executed
}
}}; // this statement placed inside the init() method
The Runnable Interface
Runnable is an interface that contains the
run() method
One of the constructors for Thread:
public Thread(Runnable r)
Can create a thread by giving it an
argument (object) that implements run()
alternative to extending thread and then
overriding run()
Thread Issues
Deadlock
some methods have been deprecated
because of this possibility
Synchronization
several threads running the same method
and/or updating the same data
Networking
CS 21b
Client/Server Computing
Communication over the network often
occurs between a client and a server
A server listens for connection requests
and then responds to messages
A client establishes a connection to a
server and then sends messages
TCP/IP: abstract layer that simplifies the
above activities
Hosts, Ports, and Sockets
Computers on the network are (uniquely)
specified by a host name or an IP address
Communication between hosts occurs
through their ports
each port allows several connections
Socket
connection handle that facilitates
communication over the network
Networking in Java
java.net package
import java.net.*;
Most important classes
Socket
ServerSocket
URL (discussed earlier)
The Socket class
Constructor requires a host and port that
the client intends to connect to
Useful Socket methods
InputStream getInputStream()
OutputStream getOutputStream()
Use file/stream interfaces to carry out the
communication
The ServerSocket class
Constructor requires a port number that
the server wishes to listen from
accept() method returns a Socket object
once a connection from a client has been
established
blocks (hangs) until the connection occurs
On the Server Program ...
Create a ServerSocket object
specify port
Invoke accept() on that object
Obtain Socket object
returned by accept()
Obtain I/O streams from the socket
carry out communication using these
streams
On the Client Program ...
Create Socket object
specify host and port of server
Obtain I/O streams from the socket
carry out communication using these
streams
* execute the server before the client
Allowing Multiple
Connections to a Server
Use Threads
Have a loop that continuously calls
accept()
main thread
Create and start a thread whenever
accept() returns a socket
facilitate communication on the socket using
a separate thread