Title: Threads in Java
1Threads in Java
2What Is a Thread?
- Familiar with writing sequential programs
- At any given time during the runtime of the
program, there is a single point of execution. - The program has a beginning, an execution
sequence, and an end - So do threads except that they run within a
program
3Threads run within Programs
- A thread itself is not a program it cannot run
on its own. - A Thread runs within a program and can execute a
set of instructions completely independent of
other threads in the same process
4Why are threads useful?
- Can be doing multiple things (multiple execution
paths) at once. - Example Browser
- Loading an applet
- Scrolling down a page
- Printing
5Threads
- Lightweight process
- A thread is similar to a real process in that a
thread and a running program are threads of
execution - A thread takes advantage of the resources
allocated for that program instead of having to
allocate those resources again
6Threads
- A thread has its own stack and program counter
for example.) - The code running within the thread works only
within the context implied by the stack and PC so
also called a execution context
7A Thread Example
// This class extends the Thread class class
MyThread extends Thread // Override the
Thread's class run() method public void run()
System.out.println("Hello there, from "
getName())
From Berg Chapter 11 see references
8An example
public class ExtendThr static public void
main(String s) MyThread Thread_a,
Thread_b // Define the threads Thread_a
new MyThread() // Create MyThread object
Thread_b new MyThread() // Create another
MyThread object Thread_a.start() // Start
the run() method in thread a
Thread_b.start() // Start the run() method in
thread b
From Berg Chapter 11 see references
9Creating and Starting a Thread
public class Echo extends Thread private
String word private int waitTime // in
millisecs public Echo(String word, int
waitTime) this.word word this.waitTime
waitTime Modified From Arnold and
Gosling Chapter 9 see references
10Creating and Starting a Thread
public void run( ) try while (true)
System.out.print(word )
sleep(waitTime)
catch (InterruptedException e) return()
// end the thread
11Creating and Starting a Thread
public static void main(String args) Echo
e1 new Echo(Foo, 200) Echo e2
new Echo(Bar, 200)
12An Alternate Mechanism
// Class the implements the Runnable
interface class MyThread2 implements Runnable
public void run() System.out.println("Hi
there, from "
Thread.currentThread().getName())
From Berg Chapter 11 see references
13An Alternate Mechanism
public class RunnableThr static public void
main(String s) MyThread2 work2do //
Object that has work to be done Thread
a_thread, b_thread // A thread object on which
to run the work // Create the MyThread2
object work2do new MyThread2()
14An Alternate Mechanism
// Create a thread with the MyThread2 object as
its target a_thread new Thread(work2do)
b_thread new Thread(work2do) // Start
the thread which will call run() in the target
a_thread.start() b_thread.start()
15A Sample Use
- Suppose that we have a server that has many
clients connected to it - We would like to start a new thread for each
client connection - What happens if we do not?
- Our server waits for a connection with accept and
when a connection is made a new thread to handle
that connection is created - Example from Berg Chapter 4 see references
16A Server Example
public class MultiThreadedServer public
static void main( String args ) throws
Exception // create a server side
socket - same as before ServerSocket server
new ServerSocket( 9999 )
Need a server socket to listen for connections
17A Server Example
block
while( true ) Socket socket
server.accept() new ThreadedSocket( socket
).start()
Start the thread
Pass the socket along
Create a Thread object
18A Server Example
class ThreadedSocket extends Thread
ThreadedSocket( Socket socket ) this.socket
socket //
Remember the socket
19A Server Example
public void run() try // create the
Objects for the Client
ObjectOutputStream output
new ObjectOutputStream( socket.getOutputStream()
) output.writeObject(
stuffForClient) socket.close()
catch( Exception e ) e.printStackTrace()
20Sharing Data
- In our previous example the socket class was
never shared by more than one thread because
every accept inside the while results in a new
thread - What if that were not the case?
- Suppose we had the notion of an account that
would be shared across threads
21Synchronized Methods
public class Account private double
balance public Account(double initial)
balance initial public synchronized
double getBalance() return balance
public synchronized double deposit(double amt)
balance amt
One at a time
22Synchronized Methods
- With synchronized two or more running threads are
guaranteed not to interfere with one another - If there are read and write methods they should
be synchronized - Another reason for accessors
- Static methods may also be locked class wide
lock - Why doesnt the constructor need to be
synchronized?
23Synchronized Statements
- The Synchronized statement enables you to execute
synchronized code that locks an object without
invoking a Synchronized method - The Synchronized statement has two parts
- An object to be locked
- A statement to execute when the lock is obtained
24Synchronized Statements
// in some class public static void abs(int
values) synchronized (values) for (int
i 0 i lt values.length I) if
(valuesi lt 0 ) valuesi - valuesi
25Selected References
- Advanced Techniques for Java Developers,Berg
Fritzinger, Chapter 11 Wiley, 1999 - The online Java Tutorial http//java.sun.com/docs/
books/tutorial/essential/threads/ - The Java Programming Language , K.Arnold and J.
Gosling , Addison-Wesley , 1996 Chapter 9