Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read."— Presentation transcript:

1 Threads

2 Overview

3 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

4 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.

5 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.

6 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.

7

8 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.

9

10 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.

11 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.

12 Java Threads Java threads are managed by the JVM Java threads may be created by:  Extending Thread class  Implementing the Runnable interface

13 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:example

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

15 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.

16 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.

17 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.

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

19 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(); }

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

21 Java Thread States

22 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.

23 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:SleepMessage

24 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

25 Creating Multiple Thread Example

26 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

27 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

28 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

29 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.

30 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 Example by using synchronization Example

31 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() ExampleExample final void notifyAll()


Download ppt "Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read."

Similar presentations


Ads by Google