Threads and Multithreading

Slides:



Advertisements
Similar presentations
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Advertisements

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 24 Multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Java Threads CS Introduction to Operating Systems.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 29 Multithreading /
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
Multithreading / Concurrency 1. Thread Thread: single sequential flow of control within a program Single-threaded program can handle one task at any time.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
Internet Software Development Controlling Threads Paul J Krause.
Threads.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Multithreading in JAVA
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Multithreading (Based on Chapter 29 (Multithreading) Liang book and Chapter 5 (Threads) Elliotte Rusty book) Dr. Tatiana Balikhina 1.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Multithreading The objectives of this chapter are:
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Chapter 30 Multithreading and Parallel Programming
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreaded Programming in Java
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Multithreading Chapter 23.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads and Multithreading Mrs. Reetu Dahiya| unit 6

Threads & multithreading Thread: single sequential flow of control within a program Single-threaded program can handle one task at any time. Multitasking allows single processor to run several concurrent threads. Most modern operating systems support multitasking. We know that a thread is a line of execution. It is the smallest unit of code that is dispatched by the scheduler and a process is a program in execution. However, a process can contain multiple threads to execute its difference sections and this is called multithreading.

Creating threads in Java: Extend java.lang.Thread class run() method must be overridden (similar to main method of sequential program) run() is called when execution of the thread begins A thread terminates when run() returns start() method invokes run() Calling run() does not create a new thread Implement java.lang.Runnable interface

Thread States A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.

Thread termination A thread becomes Not Runnable when one of these events occurs: Its sleep method is invoked. The thread calls the wait method to wait for a specific condition to be satisifed. The thread is blocking on I/O.

Creating Threads Example 1 class Output extends Thread { private String toSay; public Output(String st) { toSay = st; } public void run() { try { for(;;) { System.out.println(toSay); sleep(1000); } catch(InterruptedException e) { System.out.println(e); class Program { public static void main(String [] args) { Output thr1 = new Output(“Hello”); Output thr2 = new Output(“There”); thr1.start(); thr2.start(); } main thread is just another thread (happens to start first) main thread can end before the others do any thread can spawn more threads

Creating Threads (method 2) Advantage of Using Runnable implementing Runnable interface virtually identical to extending Thread class must still define the run()method setting up the threads is slightly different remember - can only extend one class implementing runnable allows class to extend something else

Creating Threads Example 2 class Output implements Runnable { private String toSay; public Output(String st) { toSay = st; } public void run() { try { for(;;) { System.out.println(toSay); Thread.sleep(1000); } catch(InterruptedException e) { System.out.println(e); class Program { public static void main(String [] args) { Output out1 = new Output(“Hello”); Output out2 = new Output(“There”); Thread thr1 = new Thread(out1); Thread thr2 = new Thread(out2); thr1.start(); thr2.start(); } main is a bit more complex everything else identical for the most part

Thread methods isAlive() method used to find out the state of a thread. returns true: thread is in the Ready, Blocked, or Running state returns false: thread is new and has not started or if it is finished. interrupt() f a thread is currently in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is awakened and enters the Ready state, and an java.io.InterruptedException is thrown. The isInterrupt() method tests whether the thread is interrupted.

The deprecated stop(), suspend(), and resume() Methods NOTE: The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods are deprecated (or outdated) because they are known to be inherently unsafe. You should assign null to a Thread variable to indicate that it is stopped rather than use the stop() method.

Thread Priority Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5). You can reset the priority using setPriority(int priority). Some constants for priorities include Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY By default, a thread has the priority level of the thread that created it.

Thread Synchronization A shared resource may be corrupted if it is accessed simultaneously by multiple threads. Example: two unsynchronized threads accessing the same bank account may cause conflict.

What, then, caused the error in the example What, then, caused the error in the example? Here is a possible scenario Effect: Task 1 did nothing (in Step 4 Task 2 overrides the result) Problem: Task 1 and Task 2 are accessing a common resource in a way that causes conflict. Known as a race condition in multithreaded programs. A thread-safe class does not cause a race condition in the presence of multiple threads. The Account class is not thread-safe.

synchronized Problem: race conditions Solution: give exclusive access to one thread at a time to code that manipulates a shared object. Synchronization keeps other threads waiting until the object is available. The synchronized keyword synchronizes the method so that only one thread can access the method at a time. The critical region in the Listing 29.7 is the entire deposit method. One way to correct the problem in Listing 29.7: make Account thread-safe by adding the synchronized keyword in deposit:   public synchronized void deposit(double amount)

Synchronizing Instance Methods and Static Methods A synchronized method acquires a lock before it executes. Instance method: the lock is on the object for which it was invoked. Static method: the lock is on the class. If one thread invokes a synchronized instance method (respectively, static method) on an object, the lock of that object (respectively, class) is acquired, then the method is executed, and finally the lock is released. Another thread invoking the same method of that object (respectively, class) is blocked until the lock is released.

Synchronizing Instance Methods and Static Methods With the deposit method synchronized, the preceding scenario cannot happen. If Task 2 starts to enter the method, and Task 1 is already in the method, Task 2 is blocked until Task 1 finishes the method.

Synchronizing Statements Invoking a synchronized instance method of an object acquires a lock on the object. Invoking a synchronized static method of a class acquires a lock on the class. A synchronized block can be used to acquire a lock on any object, not just this object, when executing a block of code. synchronized (expr) { statements; }   expr must evaluate to an object reference. If the object is already locked by another thread, the thread is blocked until the lock is released. When a lock is obtained on the object, the statements in the synchronized block are executed, and then the lock is released.

Synchronizing Statements vs. Methods Any synchronized instance method can be converted into a synchronized statement. Suppose that the following is a synchronized instance method:   public synchronized void xMethod() { // method body } This method is equivalent to public void xMethod() { synchronized (this) {

Synchronization Using Locks A synchronized instance method implicitly acquires a lock on the instance before it executes the method. You can use locks explicitly to obtain more control for coordinating threads. A lock is an instance of the Lock interface, which declares the methods for acquiring and releasing locks. newCondition() method creates Condition objects, which can be used for thread communication.

Deadlock Sometimes two or more threads need to acquire the locks on several shared objects. This could cause deadlock, in which each thread has the lock on one of the objects and is waiting for the lock on the other object. In the figure below, the two threads wait for each other to release the in order to get a lock, and neither can continue to run.

Questions?

Thankyou