Multi Threading.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Practice Session 7 Synchronization Liveness Guarded Methods Model
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Threading and Concurrency COM379T John Murray –
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
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
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
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.
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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Java Thread Programming
Multithreading The objectives of this chapter are:
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Threaded Programming in Python
Multithreading Lec 23.
Chapter 13: Multithreading
Multi-processor Scheduling
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
Multithreading in Java
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Dr. Mustafa Cem Kasapbaşı
Threaded Programming in Python
21 Threads.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multi Threading

A Program under execution is called Process, i A Program under execution is called Process, i..e when a Program is loaded into main memory and starts running, it is Process. A Thread is Light Weight Process. A Process under execution has below segments in memory Code, Data, Stack, Heap. But a thread may have only Stack or Heap, and other segments are shared with the Main thread. A Thread is a separate flow of execution. It is required to create multiple Threads to perform multiple actions simultaneously. Hence, using multi threading is a cheaper solution(uses less Memory) compared to using multiple processes. Java has built in support for Multi Threading.

Code(code under execution) Stack Data(to store static data) Heap Stack(for method invocation) Snapshot of Running Thread Heap(dynamic memory allocation) Snapshot of Running Process

Hence it consumes less memory and starts faster, compared to a Process. A process under execution has two cycles. CPU Cycle I/O Cycle One more advantages of Thread over Process, is Threads use CPU more effectively, compared to Processes. When one thread performs I/O, another thread can be busy with CPU. And hence, Effective usage of CPU Time. Actually, CPU executes only one Thread at a time. But CPU switches between different Threads of a Process, hence we feel that multiple threads are executed simultaneously. Java has built in support for Multithreading.

In Java there are two ways to create and start a new Thread. By extending from java.lang.Thread class 2. By implementing java.lang.Runnable interface

Below are steps involved to create and start Thread, using Thread class Write a class which extends from Thread class. Override public void run() method in class created above. Write business logic which need to be executed in new thread, in run() method of step2. In main method Create an object of Class of Step1 With the object, invoke start() method

Thread.sleep(2000); causes delay in execution of current thread. Join() method The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

Below are steps involved to create and start Thread, using Runnable interface Write a class which implements Runnable interface. Implement public void run() method in class created above. Write business logic which need to be executed in new thread, in run() method of step2. In main method Create an object of Class of Step1 Create a Thread object, by passing object(created in step 4) as parameter to Thread constructor With the Thread object(created in step 5), invoke start() method

Thread priority By default all the threads created, get medium priority, unless a specific priority explicitly is set to the thread. Below are the priority related constants provided in Thread class. Thread.MIN_PRIORITY (value is 0) Thread.NORM_PRIORITY (value is 5, which is default priority) Thread.MAX_PRIORITY (value is 10) Any numeric value between 0 and 10 can be set as priority to a Thread. Below are priority related methods provided in Thread class void setPriority(int priority); int getPriority(); A thread with high priority gets allocated with more CPU time, compared to threads with relatively low priority threads. Hence a thread with high priority threads executes faster, compared to low priority threads.

synchronized keyword Synchronized keyword can be used with either a method or a block. A method declared as synchronized can be executed by only one thread at a time. once the thread starts executing a synchronized method, the thread is not interrupted, until the thread completes execution of the method. Instead of declaring complete method as synchronized, it is possible to declare a block with few statements as synchronized. In other words, a method or block declared as synchronized is atomic, which means it gets executed completely without interruption in between. Synchronized keyword need to be used only where ever required, when it is over used, it may adversely affect the performance of Application.

public static void main(String args[]) { Thread and Inner Class Instead of creating a dedicated outer class for a Thread, an inner class(with run method) can be created for a Thread. Below is sample code of the same #1. public static void main(String args[]) { //Named object and Anonymous inner class Thread t1=new Thread(){ public void run(){ //Thread code here } }; t1.start(); //code running in main thread #2. public static void main(String args[]) new Thread( new Runnable() { public void run() { //thread code here }).start(); //code in main thread here

These methods can be used to solve producer consumer related problems. wait(), notify() and notifyAll() As known above methods are final methods defined in java.lang.Object class. Hence these methods are available in each and every class, because Object class is base class of all classes, in Java. These methods can be invoked only from synchronized block or synchronized method. wait(); - It tells the calling thread to give up the lock and go to sleep until some other thread enters calls notify() method on same object. notify(); -It wakes up one single thread that called wait() on the same object. notifyAll(); - It wakes up all the threads that called wait() on the same object. These methods can be used to solve producer consumer related problems.

Downloader Thread downloads packets, adds to Queue. Packet Queue Display Thread, which reads packets, from Queue, and displays/renders on screen Downloader Thread, which downloads packets, and puts in to Queue Here Display Thread, need to continuously check(with a infinite loop or so) Packet Queue, to find if new Packets are available, which may not be a professional approach. As continuously checking Packet Queue, may waste CPU time, and may adversely affect performance of overall Application. This problem can be solved better, by using wait() and notify(). Below are the steps involved… Downloader Thread downloads packets, adds to Queue. Calls notify() method on Queue, which wakes up Display Thread. Now display Thread reads packets from Queue, processes them. Calls wait() method on Queue, which goes on sleep, until notify() is called by Downloader Thread.

ThreadPool What is Thread Pool? It’s a pool of worker threads with life cycle as follows: 1. Assign a new task to execute 2. Execute it 3. Go back to Pool, waiting for next task Why Thread Pools? In many server applications, we may want to process each client request in parallel. For that matter, we can choose traditional approach of creating one thread per request. Disadvantage of using Traditional one thread per task approach The overhead of creating a new thread for each request is significant. Server that processing requests can spend more time and consume more system resources in creating and destroying threads than it would processing actual client requests. Another Advantage of Thread pool is limit maximum number of threads running at any point of time.

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.

Deadlock example Thread t1 Thread t2 Step3 Tries to Lock str2 Step1