Top Banner
Java Threads Java Threads Representation and Management of Data on the Internet
34

Java Threads Representation and Management of Data on the Internet.

Jan 02, 2016

Download

Documents

Francis Summers
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Threads Representation and Management of Data on the Internet.

Java ThreadsJava Threads

Representation and

Management of Data on the

Internet

Page 2: Java Threads Representation and Management of Data on the Internet.

Introduction

It would be nice if we could focus our attention on performing only one action at

a time and performing it well, but that’s usually difficult to do. The human body

performs a great variety of operations in parallel—or, as we’ll say throughout this

chapter, concurrently.

•Respiration,

• blood circulation,

•digestion, thinking and walking,

for example, can occur

•concurrently, as can all the senses—sight, touch, smell, taste and hearing.

Page 3: Java Threads Representation and Management of Data on the Internet.

Computers, too, can perform operations concurrently.

It’s common for personal computers to compile a program, send a file to a printer and

receive electronic mail messages over a network concurrently.

Only computers that have multiple processors can truly execute multiple instructions

concurrently.

Operating systems on single-processor single-processor computers create the illusion of concurrent

execution by rapidly switching between activities, but on such computers only a single

instruction can execute at once.

Today’s multicore computers have multiple processors multiple processors that enable computers to perform

tasks truly concurrently.

.

Page 4: Java Threads Representation and Management of Data on the Internet.

Java Concurrency

• Java makes concurrency available to you through the

language and APIs.

• Java programs can have multiple threads of execution,

where each thread has its own method-call stack and

program counter, allowing it to execute concurrently

with other threads while sharing with them application-

wide resources such as memory.

• This capability is called multithreading.

Page 5: Java Threads Representation and Management of Data on the Internet.

Concurrent Programming UsesConcurrent Programming Uses

• We’ll discuss many applications of concurrent programming. For example,

when downloading a large file (e.g., an image, an audio clip or a video clip)

over the Internet, the user may not want to wait until the entire clip

downloads before starting the playback. To solve this problem, multiple

threads can be used—one to download the clip, and another to play it.

• These activities proceed concurrently.

• To avoid choppy playback, the threads are synchronized (that is, their actions

are coordinated) so that the player thread doesn’t begin until there’s a

sufficient amount of the clip in memory to keep the player thread busy.

• The Java Virtual Machine (JVM) creates threads to run programs and threads

to perform housekeeping tasks such as garbage collection.

Page 6: Java Threads Representation and Management of Data on the Internet.

Thread States: Life Cycle of a ThreadThread States: Life Cycle of a Thread

At any time, a thread is said to be in one of several thread

states—illustrated in following the UML state diagram

Page 7: Java Threads Representation and Management of Data on the Internet.

New and Runnable States

A new thread begins its life cycle in the new state. It remains in this state until the program

starts the thread, which places it in the runnable state. A thread in the runnable state is

considered to be executing its task.

Waiting State

Sometimes a runnable thread transitions to the waiting state while it waits for another

thread to perform a task. A waiting thread transitions back to the runnable state only

when another thread notifies it to continue executing.

Timed Waiting State

A runnable thread can enter the timed waiting state for a specified interval of time. It

transitions back to the runnable state when that time interval expires or when the event

it’s waiting for occurs. Timed waiting and waiting threads cannot use a processor, even if

one is available..

Page 8: Java Threads Representation and Management of Data on the Internet.

Blocked State

A runnable thread transitions to the blocked state when it attempts to perform a task that

cannot be completed immediately and it must temporarily wait until that task completes.

For example, when a thread issues an input/output request, the operating system blocks

the thread from executing until that I/O request completes—at that point, the blocked

thread transitions to the runnable state, so it can resume execution. A blocked thread

cannot use a processor, even if one is available.

Terminated State

A runnable thread enters the terminated state (sometimes called the dead state) when it

successfully completes its task or otherwise terminates (perhaps due to an error). In the

UML state diagram of Fig. 26.1, the terminated state is followed by the UML final state

(the bull’s-eye symbol) to indicate the end of the state transitions.a

Page 9: Java Threads Representation and Management of Data on the Internet.

Thread Priorities and Thread Priorities and Thread SchedulingThread Scheduling

• Every Java thread has a thread priority that helps

determine the order in which threads are scheduled.

• Each new thread inherits the priority of the thread that

created it.

• Higher-priority threads are more important to a

program and should be allocated processor time before

lower-priority threads.

Page 10: Java Threads Representation and Management of Data on the Internet.

Multitasking and Multithreading

• Multitasking refers to a computer's ability to perform multiple jobs concurrently– more than one program are running concurrently, e.g., UNIX

• A thread is a single sequence of execution within a program

• Multithreading refers to multiple threads of control within a single program– each program can run multiple threads of control within it,

e.g., Web Browser

Page 11: Java Threads Representation and Management of Data on the Internet.

Concurrency vs. ParallelismConcurrency vs. ParallelismCPU CPU1 CPU2

Page 12: Java Threads Representation and Management of Data on the Internet.

What are Threads Good For?What are Threads Good For?

• To maintain responsiveness of an application

during a long running task.

• To enable cancellation of separable tasks.

• Some problems are intrinsically parallel.

• To monitor status of some resource (DB).

• Some APIs and systems demand it.

Page 13: Java Threads Representation and Management of Data on the Internet.

Application ThreadApplication Thread

• When we execute an application:– The JVM creates a Thread object whose task is

defined by the main() method

– It starts the thread

– The thread executes the statements of the program

one by one until the method returns and the thread

dies

Page 14: Java Threads Representation and Management of Data on the Internet.

Multiple Threads in an ApplicationMultiple Threads in an Application

• Each thread has its private run-time stack

• If two threads execute the same method,

each will have its own copy of the local

variables the methods use.

Page 15: Java Threads Representation and Management of Data on the Internet.

Creating ThreadsCreating Threads

• There are two ways to create our own

Thread object

1. Subclassing the Thread class and

instantiating a new object of that class

2. Implementing the Runnable interface

• In both cases the run() method should

be implemented

Page 16: Java Threads Representation and Management of Data on the Internet.

Creating and Starting Creating and Starting ThreadsThreads

• Creating a thread in Java is done like this:

• To start the thread you will call its start()

method, like this:

Page 17: Java Threads Representation and Management of Data on the Internet.

• There are two ways to specify what code

the thread should execute.

• The firstfirst is to create a subclass of Thread

and override the run() method.

• The secondsecond method is to pass an object

that implements Runnable to the Thread

constructor.

Page 18: Java Threads Representation and Management of Data on the Internet.

First way: Thread Subclass

• The first way to specify what code a thread is to run, is to create a subclass of Thread , is to create a subclass of Thread

and override the run() method. and override the run() method. The run() method is what is executed by the thread

after you call start(). Here is an example:

• To create and start the above thread you can do like this:

• hen the run() method executes it will print out the text "MyThread running".

Page 19: Java Threads Representation and Management of Data on the Internet.

Another example: Extending Thread

public class ThreadExample extends Thread {

public void run () {

for (int i = 1; i <= 100; i++) {

System.out.println(“Thread: ” + i);

}

}

}

To create and start the above thread

ThreadExample thread1= new ThreadExample;

Thread1.strat();

Page 20: Java Threads Representation and Management of Data on the Internet.

Second way: Runnable Interface Implemention

• The second way to specify what code a thread should run is by

creating a class that implements java.lang.Runnable.

• The Runnable object can be executed by a Thread.

• To have the run() method executed by a thread, pass an instance of

MyRunnable to a Thread in its constructor. Here is how that is done:

• MyRunnable runthread= new MyRunnable();

• Thread thread1= newThread(runthread);

Page 21: Java Threads Representation and Management of Data on the Internet.

Another Example: Another Example: Implementing RunnableImplementing Runnable

public class RunnableExample implements Runnable {

public void run () {

for (int i = 1; i <= 100; i++) {

System.out.println (“Runnable: ” + i);

} } }

• To have the run() method executed by a thread

RunableExample myrunable= new RunableExample();

Thread thread1= new Thread (myrunable);

thread1.start();

Page 22: Java Threads Representation and Management of Data on the Internet.

Common Pitfall: Calling run() instead of start()

• When creating and starting a thread a

common mistake is to call the run()

method of the Thread instead of

start(), like this:

Page 23: Java Threads Representation and Management of Data on the Internet.

Thread MethodsThread Methods

void start()

– Creates a new thread and makes it runnable

– This method can be called only once

void run()

– The new thread begins its life inside this method

void stop() (deprecated)

– The thread is being terminated

Page 24: Java Threads Representation and Management of Data on the Internet.

Thread MethodsThread Methods

• yield()– Causes the currently executing thread

object to temporarily pause and allow other threads to execute

– Allow only threads of the same priority to run

• sleep(int m)/sleep(int m,int n)  – The thread sleeps for m milliseconds, plus n

nanoseconds

Page 25: Java Threads Representation and Management of Data on the Internet.

SchedulingScheduling

• Thread scheduling is the mechanism

used to determine how runnable

threads are allocated CPU time

• A thread-scheduling mechanism is

either preemptive or nonpreemptive

Page 26: Java Threads Representation and Management of Data on the Internet.

Preemptive SchedulingPreemptive Scheduling

• Preemptive scheduling – the thread

scheduler preempts (pauses) a running

thread to allow different threads to execute

• Nonpreemptive scheduling – the scheduler

never interrupts a running thread

• The nonpreemptive scheduler relies on the

running thread to yield control of the CPU so

that other threads may execute

Page 27: Java Threads Representation and Management of Data on the Internet.

StarvationStarvation

• A nonpreemptive scheduler may cause

starvation (runnable threads, ready to

be executed, wait to be executed in

the CPU a lot of time, maybe even

forever)

• Sometimes, starvation is also called a

livelock

Page 28: Java Threads Representation and Management of Data on the Internet.

Time-Sliced Scheduling Time-Sliced Scheduling

• Time-sliced scheduling – the scheduler allocates a period of time that each thread can use the CPU– when that amount of time has elapsed, the

scheduler preempts the thread and switches to a different thread

• Nontime-sliced scheduler – the scheduler does not use elapsed time to determine when to preempt a thread– it uses other criteria such as priority or I/O status

Page 29: Java Threads Representation and Management of Data on the Internet.

Java SchedulingJava Scheduling

• Scheduler is preemptive and based on

priority of threads

• Uses fixed-priority scheduling:

– Threads are scheduled according to their

priority w.r.t. other threads in the ready

queue

Page 30: Java Threads Representation and Management of Data on the Internet.

Java SchedulingJava Scheduling

• The highest priority runnable thread is always

selected for execution above lower priority threads

• When multiple threads have equally high priorities,

only one of those threads is guaranteed to be

executing

• Java threads are guaranteed to be preemptive-but

not time sliced

• Q: Why can’t we guarantee time-sliced scheduling?

What is the danger of such scheduler?

Page 31: Java Threads Representation and Management of Data on the Internet.

Thread PriorityThread Priority

• Every thread has a priority

• When a thread is created, it

inherits the priority of the thread

that created it

• The priority values range from 1 to

10, in increasing priority

Page 32: Java Threads Representation and Management of Data on the Internet.

Thread Priority (cont.)Thread Priority (cont.)

• The priority can be adjusted subsequently

using the setPriority() method

• The priority of a thread may be obtained

using getPriority()

• Priority constants are defined:

– MIN_PRIORITY=1

– MAX_PRIORITY=10

– NORM_PRIORITY=5

Page 33: Java Threads Representation and Management of Data on the Internet.

Some NotesSome Notes

• Thread implementation in Java is actually

based on operating system support

• Some Windows operating systems

support only 7 priority levels, so different

levels in Java may actually be mapped to

the same operating system level

• What should we do about this?

Page 34: Java Threads Representation and Management of Data on the Internet.

Daemon ThreadsDaemon Threads

• Daemon threads are “background” threads,

that provide services to other threads, e.g.,

the garbage collection thread

• The Java VM will not exit if non-Daemon

threads are executing

• The Java VM will exit if only Daemon threads

are executing

• Daemon threads die when the Java VM exits