Unit - IV Multi-Threading

Similar documents
04-Java Multithreading

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

JAVA. Lab 12 & 13: Multithreading

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Synchronization synchronization.

Module - 4 Multi-Threaded Programming

Object Oriented Programming (II-Year CSE II-Sem-R09)

Multithreaded Programming

7. MULTITHREDED PROGRAMMING

Amity School of Engineering

Object Oriented Programming. Week 10 Part 1 Threads

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Software Practice 1 - Multithreading

Concurrent Programming using Threads

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming

Unit III Rupali Sherekar 2017

Object-Oriented Programming Concepts-15CS45

Multithread Computing

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

CS 556 Distributed Systems

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Threads Chate Patanothai

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

JAVA - MULTITHREADING


Unit 5 - Exception Handling & Multithreaded

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

By: Abhishek Khare (SVIM - INDORE M.P)

we dont take any liability for the notes correctness.

Multithreading using Java. Dr. Ferdin Joe John Joseph

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

UNIT V CONCURRENT PROGRAMMING

MULTI-THREADING

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

EDAF65 Processes and Threads

EDA095 Processes and Threads

Techniques of Java Programming: Concurrent Programming in Java

CMSC 132: Object-Oriented Programming II. Threads in Java

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Multithreaded Programming

Synchronized Methods of Old Versions of Java

Java Threads. Introduction to Java Threads

Java Threads. Written by John Bell for CS 342, Spring 2018

CIS233J Java Programming II. Threads

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Contents. 6-1 Copyright (c) N. Afshartous

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

Animation Part 2: MoveableShape interface & Multithreading

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

UNIT:5 EXCEPTION HANDLING & MULTITHREADED

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Threads in Java (Deitel & Deitel)

Chapter 32 Multithreading and Parallel Programming

Basics of. Multithreading in Java

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

Multithreading Pearson Education, Inc. All rights reserved.

Programming Java. Multithreaded Programming

CS360 Lecture 12 Multithreading

Chapter 19 Multithreading

Multi-threading in Java. Jeff HUANG

EDA095 Processes and Threads

Java Threads. COMP 585 Noteset #2 1

Introduction to Java Threads

Multithreaded Programming

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

User Space Multithreading. Computer Science, University of Warwick

Performance Throughput Utilization of system resources

Advanced Concepts of Programming

Overview of Java Threads (Part 2)

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Multithreaded Programming

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Multithreading in Java Part 2 Thread - States JAVA9S.com

Threads Questions Important Questions

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

G52CON: Concepts of Concurrency

public class Shared0 { private static int x = 0, y = 0;

Time-Sharing Operating Systems. EDA095 Processes and Threads. Process Creation. The Content of a Process

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Concurrent Computing CSCI 201 Principles of Software Development

Java s Implementation of Concurrency, and how to use it in our applications.

What is a thread anyway?

Hosur road, 1km before Electronic City, Bengaluru Date : 4/10/17 Max Marks : 50. Subject & Code : JAVA and J2EE (10CS753) Section : A,B,C

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

Component-Based Software Engineering

Programming Language Concepts: Lecture 11

CERTIFICATION OBJECTIVES

JOURNAL OF OBJECT TECHNOLOGY

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering

Transcription:

Unit - IV Multi-Threading 1

Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first program completed and released the resources voluntarily. In this procedure the main disadvantage is most of the times the CPU is kept as ideal. sothat t CPU resources are getting wasted. 2

Multi Programming Multi Programming means multiple programs are running at the same time onasingle processor. So the advantage is the CPU can be utilized more efficiently than uni processing. 3

Multi Processing In this procedure more than one processor will execute the programs parallel. Because of two processors multiple (or) parallel execution is possible. 4

Multi Tasking Multi Tasking means multiple parts of the program is getting started at the same time. This multi tasking is possible on single processor and multiple processors also. In multi tasking for each and every process will be allocated a time period. Multi Tasking=Multi Programming + Time Sharing. 5

Multi Tasking There are two distinct types of multi tasking 1) Process-based 2) Thread-based A process is a program that is executing. Process-based multi tasking allows computer to run two or more programs concurrently. E.g., Process-based multitasking allows computer to run the java compiler at the same time we are using a text editor. 6

Thread-based Multi Tasking In thread-based d multi tasking environment asingle program can perform two or more tasks simultaneously. E.g., A text Editor can format text at the same time it can perform printing. 7

Thread A thread is nothing but separate part of execution. Whenever thread is created it will not occupy any separate memory. But it will share the memory which is already allocated to a program. 8

Process-based vs Thread-based Processes are heavy weight tasks that require their own separate address spaces. Interprocess communication is expensive and limited. Context switching from one process to another is also costly. 9

Process-based vs Thread-based Threads are light weight process. They share the same address space and cooperatively share the same heavy weight process. Inter thread communication is inexpensive. Context switching from one thread to the next is low cost. 10

Single-thread System Single-thread System use an approach called an event loop with pooling. A Single thread of control runs in an infinite loop, pooling a single event queue to decide what to do next. In a single-threaded environment, when a thread blocks because it is waiting for some resources the entire program stops running. 11

Multi Thread Multithreading enables us to write very efficient programs that make maximum use of CPU. Because ideal time can be kept to a minimum. Java supports multi threading. The advantage of multi threading is that the main loop, pooling mechanism is eliminated. One thread can pause with out stopping other parts of the program. 12

Thread Life Cycle Thread can exist in several states: 1. New Born 2. Ready State 3. Running State 4. Blocked/Waiting State 5. Dead State 13

Thread States / Life Cycle of Thread 14

Thread States 15

Thread Life Cycle When a thread is dead, the same thread can t able to restart it is possible to start some other new thread. Whenever thread is dead, it is handled by ThreadDeath class in Error super class. ThreadDeath class will be invoked whenever the stop() method is called. 16

Thread Creation Implementing threads is achieved in one of two ways: - implementing the java.lang.runnable interface - extending the java.lang.thread class The Thread class defines several methods that help to manage threads: 17

Method Meaning getname Obtain a thread s name. getpriority Obtain a thread s priority. isalive Determine if a thread is still running. join Wait for a thread to terminate. run Et Entry point itfor the thread. sleep Suspend a thread for a period of time. start Start a thread by calling its run method. 18

Extending Thread Class The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread. By using start() the control passes a request to processor for allocating resources. 19

Extending Thread Class After allocating the resources the last instruction is calling the run() method. start() implicitly calls the run() method. 20

Create a thread by extending Thread class NewThread extends Thread { NewThread() { // Create a new, second thread super("demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) ){ System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println( println("child interrupted. "); } System.out.println("Exiting child thread."); }} 21

Create a thread by extending Thread class ExtendThread { public static void main(string args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } 22

Thread Priorities A thread s priority is used to decide when to switch from one running thread to the next. This is called a context switch. Thread class supporting different priorities: 1) MIN_PRIORITY 2) NORM_PRIORITY 3) MAX_PRIORITY Whenever a thread is created by default it is containing NORM_PRIORITY whose value is 5. 23

Thread Priorities MIN_PRIORITY The minimum priority that a thread can have public static final int MIN_PRIORITY NORM_PRIORITY The default priority that is assigned to a thread. public static final int NORM_PRIORITY MAX_PRIORITY The maximum priority that a thread can have public static final int MAX_PRIORITY 24

Thread Class Constructors Thread(): E.g., Allocates a new Thread Object. Thread t=new Thread(); 25

Constructors Thread(Runnable target): Allocates a new Thread object. E.g., SecondThread st= new SecondThread(); Thread t =new Thread(st); 26

Constructors Thread(Runnable target, t String name): Allocates a new Thread object. E.g., SecondThread d st=new SecondThread(); d() Thread t= new Thread(st, Secondchild ); 27

Constructors Thread(String name): Allocates a new thread. E.g., Thread t= new Thread( FirstChild ); 28

Constructors Thread(ThreadGroup dg group, String name): Allocates a new Thread object. E.g., Thread(group, null, name) ThreadGroup tg=new ThreadGroup( Image Group ); Thread t1= new Thread(tg, frist t child ); Thread t2= new Thread(tg, second child ); 29

Constructors Thread(ThreadGroup group, Runnable target): Allocates a new thread object. group - the thread group. target t - the object whose run method is called. 30

Constructors E.g., ThreadGroup tg=new ThreadGroup( Image Group ); SecondThread st= new SecondThread(); Thread t1= new Thread(tg, st); Thread t2= new Thread(tg, st); 31

Constructors Thread(ThreadGroup dg group, Runnable target, t String name): Allocates a new Thread object so that tith has target tas its run object, has the specified name as its name, and belongs to the thread group referred to by group. 32

Constructors E.g., ThreadGroup tg= new ThreadGroup( Image Group ); SecondThread st= new SecondThread(); Thread t1= new Thread(tg, st, First child ); Thread t2= new Thread(tg, st, Second child ); 33

Constructors Thread(ThreadGroup dg group, Runnable target, t String name, long StackSize): Allocates a new Thread object so that it has target as its run object, has the specified name as its name, belongs to the thread group referred to by group, and has the specified stack size. 34

Constructors E.g., ThreadGroup tg=new ThreadGroup( Image Group ); SecondThread st= new SecondThread(); Thread t1= new Thread(tg,st, first child,10); Thread t2= new Thread(tg,st, second child,10); 35

Thread Methods currentthread(): Returns a reference to the currently executing thread object. public static ti Thread currentthread() 36

Thread Methods setname: Changes the name of this thread to be equal to the argument name. public final void setname(string name) 37

Thread methods getname(): Rt Returns this thread s name. getpriority(): public final String getname() Returns this thread s priority. it public final int getpriority() it 38

Thread Methods getthreadgroup(): Returns the thread group to which this thread belongs. This method returns null if this thread has died. public final ThreadGroup getthreadgroup() 39

Thread Methods setpriority(): Changes the priority of this thread. public final void setpriority(int newpriority) This method throws 1)IllegalAccessException: If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY. 2)SecurityException: if the current thread cannot modify this thread. 40

Thread Methods E.g., ThreadTest t= new ThreadTest(); t.setpriority(thread.norm_priority+3); tp it PRIORITY+3) System.out.println(t.getPriority()); 41

Thread Methods sleep(): Causes the currently executing thread to sleep for the specified number of milliseconds. public static void sleep(long millis) throws InterruptedException - InterruptedException: if another thread has interrupted the current thread. 42

Thread methods public static void sleep(long millis, int nanos) throws InterruptedException Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds. - millis - the length of time to sleep in milliseconds. - nanos - 0-999999 additional nanoseconds to sleep. 43

Thread Methods interrupt(): t() Interrupts this thread. public void interrupt() SecurityException: if the current thread cannot modify this thread 44

Thread methods interrupted(): Tests whether the current thread has been interrupted. t public static ti boolean interrupted() t 45

Thread Methods isinterrupted(): Tests whether this thread has been interrupted. t public boolean isinterrupted() t 46

Thread Methods isalive(): Tests if this thread is alive. A thread is alive if it has been started t and has not yet died. Returns true if this thread is alive; false otherwise. public final boolean isalive() 47

Thread Methods join(): Waits for this thread to die. This method waits until the thread on which h it is called terminates. public final void join() throws InterruptedException 48

Example of isalive() and join() class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) ){ name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try y{ for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } 49

Example of isalive() and join()... class DemoJoin { public static void main(string args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); Two); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: + ob1.t.isalive()); System.out.println( println("thread Two is alive: + ob2.t.isalive()); System.out.println("Thread Three is alive: + ob3.t.isalive()); // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: + ob1.t.isalive()); System.out.println("Thread Two is alive: + ob2.t.isalive()); System.out.println("Thread Three is alive: + ob3.t.isalive()); System.out.println("Main thread exiting."); }}} 50

Thread Methods yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute. public static void yield() 51

suspend(), resume() and stop() suspend( ) and resume( ), which are methods defined by Thread, to pause and restart the execution of a thread. - final void suspend( ) - final void resume( ) The Thread class also defines a method called stop( ) that stops a thread. Its signature is shown here: - final void stop( ) 52

Example of suspend() and resume() class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println( println("new thread: " +t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 15; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(200); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } 53

Example of suspend() and resume()... class SuspendResume { public static void main(string args[]) ){ NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); try y{ Thread.sleep(1000); ob1.t.suspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.t.resume(); System.out.println("Resuming thread One"); ob2.t.suspend(); System.out.println("Suspending t tl thread Two"); Thread.sleep(1000); ob2.t.resume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted");} // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); } catch(interruptedexception e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); }} 54

Synchronization When two or more threads need access to a shared resource it is called as race condition. To avoid this race condition we need to use a mechanism called as synchronization. A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread enters in to the monitor all other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. 55

Synchronization Synchronization can be achieved in two ways: 1) Method level synchronization 2) Block level synchronization In method level synchronization the total data of method is sensitive. Where as in block level synchronization part of the method is sensitive. 56

Example: Without synchronized class Callme { void call(string msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch(interruptedexception e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg =s; t = new Thread(this); t.start(); } public void run() { target.call(msg); }} 57

Example: Without synchronized class Synch { public static void main(string args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(interruptedexception e) { System.out.println("Interrupted"); } } } Here is the output produced by this program: [Hello[Synchronized[World] ] ] 58

Example: With synchronized class Callme { synchronized void call(string msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch(interruptedexception e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } public void run() { target.call(msg); }} 59

Example: With synchronized class Synch { public static void main(string args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); // wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(interruptedexception e) { System.out.println("Interrupted"); } } } Here is the output produced by this program: [Hello] [Synchronized] [World] 60

Interthread Communication 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 the same object. notifyall( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. Example - Producer and Consumer Problem 61

Assignment 1. What is Thread? 2. How can you create thread in Java? 3. Explain the life cycle of Thread? 4. What is monitor? 5. What is the use of sychronized method and sychronized block? 6. What do mean by inter thread communication? Write the java program for producer and consumer problem? 7. How can you set thread priority? it 8. Explain the isalive(), join(), suspend(), and resume() with example. 62