Docsity

Java Multithreading: Part 1 - Introduction and Performance Improvement - Prof. Mark Llewel, Papers of Computer Science

Toggle sidebar
bg1
COP 4610L: Threading Part 1 Page 1 Mark Llewellyn ©
COP 4610L: Applications in the Enterprise
Spring 2006
Programming Multithreaded Applications in Java
Part 1
COP 4610L: Applications in the Enterprise
Spring 2006
Programming Multithreaded Applications in Java
Part 1
School of Electrical Engineering and Computer Science
University of Central Florida
Instructor : Dr. Mark Llewellyn
CSB 242, 823-2790
http://www.cs.ucf.edu/courses/cop4610L/spr2006
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d

Partial preview of the text

Download Java Multithreading: Part 1 - Introduction and Performance Improvement - Prof. Mark Llewel and more Papers Computer Science in PDF only on Docsity!

COP 4610L: Threading Part 1

Page 1

Mark Llewellyn ©

COP 4610L: Applications in the Enterprise

Spring 2006

Programming Multithreaded Applications in Java

Part 1

COP 4610L: Applications in the Enterprise

Spring 2006

Programming Multithreaded Applications in Java

Part 1

School of Electrical Engineering and Computer Science

University of Central Florida

Instructor :

Dr. Mark [email protected] 242, 823-2790http://www.cs.ucf.edu/courses/cop4610L/spr

COP 4610L: Threading Part 1

Page 2

Mark Llewellyn ©

Introduction to Threads in Java

In state-of-the art software, a program can be composed ofmultiple independent flows of control.

A flow of control is more commonly referred to as a process orthread.

In most of the Java programs that you’ve written (probably)there

was

a

single

flow

of

control.

Most

console-based

programs begin with the first statement of the method

main()

and work forward to the last statement of the method

main().

Flow of control is often temporarily passed to other methodsthrough invocations, but the control returned to

main()

after

their completion.

Programs with a single control flow are known as sequentialprocesses.

COP 4610L: Threading Part 1

Page 4

Mark Llewellyn ©

Applications running on

my office PC

COP 4610L: Threading Part 1

Page 5

Mark Llewellyn ©

Some of the processesrunning the applicationsrunning on my office PC

CPU working hard!!!

COP 4610L: Threading Part 1

Page 7

Mark Llewellyn ©

Improving Performance With Multithreading

As the diagram on the previous page implies, applicationsthat perform several tasks which are not dependent on oneanother will benefit the most from multithreading.

For example, in the previous diagram, Task 2 can only beoverlapped with Task 1 if Task 2 doesn’t depend on theresults of Task 1.

However, some overlap between the two tasks may still bepossible even if Task 2 depends on the results of Task 1.

In

this case the two tasks must communicate so that they cancoordinate their operations.

COP 4610L: Threading Part 1

Page 8

Mark Llewellyn ©

Improving Performance With Multithreading

(cont.)

Writing

multithreaded

programs

can

be

tricky

and

complicated,

particularly

when

synchronization

between

threads is required.

Although

the

human

mind

can

perform

many

functions

concurrently, people find it difficult to jump between paralleltrains of thought.

To see why multithreading can be difficult to program andunderstand, try the experiment shown on the following page.

COP 4610L: Threading Part 1

Page 10

Mark Llewellyn ©

Typical Multithreaded Applications

Used to improve the performance of applications whichrequire extensive I/O operations.

Useful

in

improving

the

responsiveness

of

GUI-based

applications.

Used when two or more clients need to run server-basedapplications simultaneously.

Note:

on

a

single

CPU

machine,

threads

don’t

actually

execute

simultaneously. Part of the JVM known as the thread scheduler time-slicesthreads which are runnable (we’ll see more of this in a bit) giving theillusion of simultaneous execution.

COP 4610L: Threading Part 1

Page 11

Mark Llewellyn ©

A multithreaded programends when all of itsindividual flows of control(threads) end.

Multithreaded Program{

statement 1;statement 2;…statement x;…statement y;…statement z; }

Thread B{

B statement 1;B statement 2;…statement r; }

Thread C{

C statement 1;C statement 2;…C statement t; }

Thread A{

A statement 1;A statement 2;…A statement m;…A statement n; }

This statement starts threadB. After starting the thread,the program continues withthe next statement.

This statement startsthread A. After startingthread A, the programcontinues with the nextstatement.

This statement inthread A starts threadC. Thread A continueswith next statement.

COP 4610L: Threading Part 1

Page 13

Mark Llewellyn ©

The Java Thread Class

java.lang.Runnable^ java.lang.Thread

+Thread()+Thread (target: Runnable)+run(): void+start(): void+interrupt(): void+isAlive(): boolean+setPriority(p: int): void+join(): void+sleep(millis: long): void+yield(): void+isInterrupted(): boolean+currentThread(): Thread

Creates a default thread.

Invoked by the JVM to execute the thread. You must override thismethod and provide the code you want your thread to execute in yourthread class. This method is never directly invoked by a the runnableobject in a program, although it is an instance method of a runnableobject. Starts the thread that causes the run() method to be invoked by the JVM Interrupts this thread. If the thread is blocked, it is ready to run again.Tests if the thread is currently running.Sets priority p (ranging from 1 to 10) for this thread. Waits for this thread to finish. Puts the runnable object to sleep for a specified time in milliseconds.

Creates a new thread to run the target object

Causes this thread to temporarily pause and allow other threads to execute

Tests if the current thread has been interruptedReturns a reference to the currently executing thread object.

COP 4610L: Threading Part 1

Page 14

Mark Llewellyn ©

Java Classes and Threads

Java

has

several

classes

that

support

the

creation

and

scheduling of threads.

The two basic ways of creating threads in Java are:

1) extending the

Thread

class

or 2) implementing the

Runnable

interface.

(Both are found in package

java.lang

.^

Thread

actually

implements

Runnable

We’ll

also

look

at

a

slightly

different

technique

for

creating

and

scheduling

threads

later

using

the

java.util.Timer

and

java.util.TimerTask

classes.

COP 4610L: Threading Part 1

Page 16

Mark Llewellyn ©

//Custom Thread ClassPublic class CustomThread extends Thread{ …

public CustomThread(…){

} //Override the run method in Thread//Tell system how to run custom threadpublic void run( ){

} //end CustomThread Class

//Client Class to utilize CustomThreadPublic class Client{ …

public void someMethod( ){

…//create a threadCustomThread thread1 =

new CustomThread(…);

//start a threadthread1.start( );… //create another threadCustomThread thread2 =

new CustomThread(…);

//start another threadthread2.start( );… } …} //end Client Class

Template for defining a thread class byextending the Thread class. Threadsthread1 and thread2 are runnable objectscreated from the CustomThread class.The start method informs the system thatthe thread is ready to run.

COP 4610L: Threading Part 1

Page 17

Mark Llewellyn ©

//Custom Thread ClassPublic class CustomThread implements Runnable{ …

public CustomThread(…){

} //Implement the run method in Runnable//Tell system how to run custom threadpublic void run( ){

} //end CustomThread Class

//Client Class to utilize CustomThreadPublic class Client{ …

public void someMethod( ){

…//create an instance of CustomThreadCustomThread custhread =

new CustomThread(…);

…//create a threadThread thread =

newThread(custhread);

…//start a threadthread.start( );… } …} //end Client Class

Template for defining a thread class byimplementing the Runnable interface. Tostart a new thread with the Runnableinterface, you must first create an instance ofthe class that implements the Runnableinterface (in this case custhread), then usethe Thread class constructor to construct athread.

COP 4610L: Threading Part 1

Page 19

Mark Llewellyn ©

// Override the run() method to tell the system what the thread will do public void run() { for (int i = 0; i < times; i++) System.out.print(charToPrint); } } // The thread class for printing number from 1 to n for a given nclass PrintNum extends Thread { private int lastNum;// Construct a thread for print 1, 2, ... ipublic PrintNum(int n) { lastNum = n; } // Tell the thread how to runpublic void run() { for (int i = 1; i <= lastNum; i++) System.out.print(" " + i); } } //end class TestThread

Overriding the run method

in the Thread class

COP 4610L: Threading Part 1

Page 20

Mark Llewellyn ©

Sample executions of classTestThread. Notice that the outputfrom the three threads is interleaved.Also notice that the output sequenceis not repeatable.