threads. overview problem multiple tasks for computer draw & display images on screen check...

31
Threads

Upload: anabel-mccormick

Post on 12-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Threads

Page 2: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Overview

Page 3: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Problem

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

Page 4: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Multitasking (Time-Sharing)

Multithreading allows two parts of the same program to run concurrently

Marathon runners sometimes are faced with a dilemma when two major races fall during the same week because they have to choose which race to run in.

They probably wish there was a way a part of them could go to one race and another part to the other race.

That can’t happen—that is, unless the runner is a Java program, because two parts of the same Java program can run concurrently by using multithreading.

Page 5: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Multitasking

Multitasking is performing two or more tasks at the same time. Nearly all operating systems are capable of multitasking by using one of two

multitasking techniques: process-based multitasking and thread-based multitasking. Process-based multitasking is running two programs concurrently. Programmers refer to a program as a process. Therefore, you could say that process-based multitasking is program-based

multitasking. Thread-based multitasking is having a program perform two tasks at the same

time. For example, a word processing program can check the spelling of words in a document while you write the document.

This is thread-based multitasking. A good way to remember the difference between process-based multitasking

and thread-based multitasking is to think of process-based as working with multiple programs and thread-based as working with parts of one program.

Page 6: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your car. Your engine keeps running regardless of whether the car is moving. Your objective is to keep your car moving as much as possible so you can get

the most miles from a gallon of gas. An idling engine wastes gas. The same concept applies to the CPU in your computer. You want your CPU cycles to be processing instructions and data rather than

waiting for something to process. A CPU cycle is somewhat similar to your engine running.

Page 7: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read
Page 8: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Overhead

Process-based multitasking has a larger overhead than thread-based multitasking.

In process-based multitasking, each process requires its own address space in memory.

The operating system requires a significant amount of CPU time to switch from one process to another process.

Programmers call this context switching, where each process (program) is a context.

Additional resources are needed for each process to communicate with each other.

In comparison, the threads in thread-based multitasking share the same address space in memory because they share the same program.

This also has an impact on context switching, because switching from one part of the program to another happens within the same address space in memory.

Likewise, communication among parts of the program happens within the same memory location.

Page 9: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read
Page 10: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Threads

A thread is part of a program that is running. Thread-based multitasking has multiple threads running at the same

time (that is, multiple parts of a program running concurrently). Each thread is a different path of execution. Let’s return to the word processing program example to see how

threads are used. Two parts of the word processor are of interest: The first is the part of the program that receives characters from the

keyboard, saves them in memory, and displays them on the screen. The second part is the portion of the program that checks spelling. Each part is a thread that executes independently of each other, even

though they are part of the same program.

Page 11: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

While one thread receives and processes characters entered into the keyboard, the other thread sleeps.

That is, the other thread pauses until the CPU is idle. The CPU is normally idle between keystrokes. It is this time period when the spell checker thread awakens and

continues to check the spelling of the document. The spell checker thread once again pauses when the next character is

entered into the keyboard. The Java run-time environment manages threads, unlike in process-

based multitasking where the operating system manages switching between programs.

Threads are processed asynchronously. This means that one thread can pause while other threads continue to

process.

Page 12: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Java Threads

Java threads are managed by the JVM

Java threads may be created by:

Extending Thread class Implementing the Runnable interface

Page 13: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Defining and Starting a Thread An application that creates an instance of Thread must provide the code

that will run in that thread. There are two ways to do this: Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain

the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the

HelloRunnable example:

Page 14: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

Page 15: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

The Thread class itself implements Runnable, though its run method does nothing.

Notice that both examples invoke Thread.start in order to start the new thread.

Page 16: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Which of these idioms should you use?

The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread.

The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread.

Page 17: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

The Thread class defines a number of methods useful for thread management.

These include static methods, which provide information about, or affect the status of, the thread invoking the method.

The other methods are invoked from other threads involved in managing the thread and Thread object.

We'll examine some of these methods in the following sections.

Page 18: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

public class Thread {public Thread(Runnable R); // Thread R.run()⇒public Thread(Runnable R, String name);public void start(); // begin thread execution...}

Page 19: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

More Thread Class Methods

public class Thread { public void run(); public void start();

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 int getPriority();public static Thread currentThread();public static void sleep(long milliseconds);public static void yield();

}

Page 20: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

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()…

Page 21: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Java Thread States

Page 22: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period.

This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

The sleep method can also be used for pacing, and waiting for another thread with duties that are understood to have time requirements.

Page 23: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be

precise, because they are limited by the facilities provided by the underlying OS.

Also, the sleep period can be terminated by interrupts, as we'll see in a later section.

In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

The SleepMessage example uses sleep to print messages at four-second intervals:

Page 24: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the

current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it

doesn't bother to catch InterruptedException. Example

Page 25: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Creating Multiple Thread

Example

Page 26: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

isAlive() and join()

How can one thread know when another thread has ended? Two ways to know this. Call isAlive() on thread that returns true if the thread is still running false

otherwise. Use join() that waits until the thread terminates. It is also used to specify a maximum amount of time to wait for the specified

thread to terminate. Example

Page 27: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Thread Priorities

Higher priority threads get more CPU time than lower priority threads. public void setPriority(int level) Level must be in between MIN_PRIORITY(1) & MAX_PRIORITY(10). NORM_PRIORITY(5). These are final variables of Thread class. public int getPriority() Example

Page 28: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Suspending, Resuming and Stopping Threads

Thread class defines suspend(), resume() and stop(). These cant be used now in java 2.0. How to pause, restart and terminate the thread. A thread is designed so that run() periodically checks to

determine whether that thread should be suspended, resume or stop its own execution.

It can be done by a flag value that indicates the execution state of the thread.

wait() and notify() can be used along with the flag. Example

Page 29: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Synchronization

When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.

The process by which this is achieved is known as synchronization. For this monitor (semaphore) is used. A monitor is an object that is used as a mutually exclusive lock

(mutex). Only one thread can own a monitor at a given time. When a thread acquires a lock it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be

suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor.

Page 30: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Using Synchronized Methods

All java objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified

with keyword synchronized. Synchronized keyword guard the state from race condition (i.e. more

than one thread are racing each other to complete the task.) Once a thread enters any synchronized method on an instance, no other

thread can enter any other synchronized method on the same instance. However non-synchronized method can be callable on that instance. Simple Example Example without synchronized Example by using synchronization

Page 31: Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read

Inter threaded Communication Inter process communication It is done via wait(), notify(), and notifyAll() methods. These methods are implemented as “final” in Object; so all classes have these

methods. All three methods can be called only from within a synchronized method. wait() tells the calling thread to give up the monitor and go to sleep until some

other thread enters the same monitor and calls notify(). notify() wakes up the first thread that called wait() on same object. notifyAll() wakes up all the threads that called wait() on same object. The

highest priority thread will run first. final void wait() throws InterruptedException final void notify() Example final void notifyAll()