Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Advertisements

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading The objectives of this chapter are:
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.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
10/10/20151 MULTITHREADED PROGRAMMING. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called.
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)
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
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 in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
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.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
Packages Packages are containers for classes that are used to keep the class name space compartmentalized.. You can define classes inside a package that.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
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.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
THREAD MODEL.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
6/11/2016 DEPT OF CSE 1 JAVA. 6/11/2016 DEPT OF CSE 2 MULTITHREADED PROGRAMMING.
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.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Multithreading The objectives of this chapter are:
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
Multithreading in Java
Multithreading programming Pavan d.m.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Multithreading in java.
Threads and Multithreading
Multithreading The objectives of this chapter are:
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading

Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread Each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.

Multi Tasking A multi tasking OS is capable of running more than one program(process) at a time. Multi tasking is achieved by periodically switching CPU from one task to another There are two distinct types of multi tasking. Process based and Thread based

Process& Thread A process is a self contained running program which has its own address space. Process based multi tasking allows to run two or more programs concurrently. Eg:-Running compiler and text editor concurrently. Smallest unit of a code that can be dispatched by the scheduler.

Thread Vs Process Multi tasking thread requires less overhead than process. Process are heavy weighted tasks requires there own address space and memory space. Inter process communication is limited and expensive, context switching is costly Threads are light weight they shares same address space[Program Counter].Inter thread communication is inexpensive and context switching is easy. Using multi threading we can make use of CPU effectively. Because idle time kept minimum. Single thread program has to wait if it has dependency

Thread Vs Process Multi tasking thread requires less overhead than process. Process are heavy weighted tasks requires there own address space and memory space. Inter process communication is limited and expensive, context switching is costly Threads are light weight they shares same address space[Program Counter].Inter thread communication is inexpensive and context switching is easy. Using multi threading we can make use of CPU effectively. Because idle time kept minimum. Single thread program has to wait if it has dependency

Thread Vs Process Multi tasking thread requires less overhead than process. Process are heavy weighted tasks requires there own address space and memory space. Inter process communication is limited and expensive, context switching is costly Threads are light weight they shares same address space[Program Counter].Inter thread communication is inexpensive and context switching is easy. Using multi threading we can make use of CPU effectively. Because idle time kept minimum. Single thread program has to wait if it has dependency

Thread Vs Process Multi tasking thread requires less overhead than process. Process are heavy weighted tasks requires there own address space and memory space. Inter process communication is limited and expensive, context switching is costly Threads are light weight they shares same address space[Program Counter].Inter thread communication is inexpensive and context switching is easy. Using multi threading we can make use of CPU effectively. Because idle time kept minimum. Single thread program has to wait if it has dependency

Thread Vs Process Multi tasking thread requires less overhead than process. Process are heavy weighted tasks requires there own address space and memory space. Inter process communication is limited and expensive, context switching is costly Threads are light weight they shares same address space[Program Counter].Inter thread communication is inexpensive and context switching is easy. Using multi threading we can make use of CPU effectively. Because idle time kept minimum. Single thread program has to wait if it has dependency

Advantages Reduces the computation time. Improves performance of an application. Threads share the same address space so it saves the memory. Context switching between threads is usually less expensive than between processes. Cost of communication between threads is relatively low.

Java Threading.. Java supports multi threading Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to others Thread priorities are integers that specify the relative priority of one thread to another. A thread's priority is used to decide when to switch from one running thread to the next, this is called context switch. A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.

A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted— no matter what it is doing—by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does _preemptive multitasking. When two threads with same priority comes OS will decide which one to invoke based on its algorithm.

Synchronization When two threads needs to access same piece of resource conflicts may happen. We must prevent one thread from writing data in to a file while other thread is I the middle of reading it. Monitor is a mechanism to synchronize the code The monitor is a control mechanism. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor. In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time.

Main Thread When a Java program starts up, one thread be main thread begins running immediately. The main thread is important for two reasons: –It is the thread from which other "child" threads will be spawned. –It must be the last thread to finish execution. When the main thread stops, your program terminates. Ref1 : CurrentThreadDemo.java

Program in brief A reference to the current thread (the main thread, in this case) is obtained by calling currentThread(), and this reference is stored in the local variable t. Next, the program displays information about the thread. The program then calls setName() to change the internal name of the thread. Information about the thread is then redisplayed. Next, a loop counts down from five, pausing one second between each line. The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in milliseconds. Notice the try/catch block around this loop. The sleep() method in Thread might throw an InterruptedException. This would happen if some other thread wanted to interrupt this sleeping one.

The thread displays, in order: –the name of the thread, its priority, and the name of its group. –By default, the name of the main thread is main. –Its priority is 5, which is the default value, and main is also –The name of the group of threads to which this thread belongs. A thread group is a data structure that controls the state of a collection of threads as a whole. This process is managed by the particular run-time environment and is not discussed in detail here. After the name of the thread is changed, t is again output. This time, the new name of the thread is displayed.

Creating a Thread Java’s multi threading is built upon two Thread class and Runnable interface Thread class defines several methods that help manage threads. A thread can be created in any one of the two ways 1.Implement the Runnable interface. 2.Extend the Thread class,

Implementing Runnable The easiest way to create a thread is to create a class that implements the Runnable interface. To implement Runnable, a class need only implement a single method called run(), which is declared like this: public void run() Inside run (), define the code that constitutes the new thread. run() can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns.

After creating a class that implements Runnable, instantiate an object of type Thread from within that class. Thread defines several constructors. The one that is like Thread(Runnable threadOb, String threadName) threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName. After the new thread is created, it will not start running until you call its start() method,which is declared within Thread. start() executes a call to run(). Ref: ThreadRunnableApplication.java

class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the 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("Child interrupted."); } System.out.println("Exiting child thread."); }

class ThreadDemo { 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) { S.O.P("Main thread interrupted."); } System.out.println("Main thread exiting."); }

Inside NewThread's constructor, a new Thread object is created by the following statement: t = new Thread(this, "Demo Thread"); Passing this as the first argument indicates that you want the new thread to call the run() method on this object. Next, start() is called, which starts the thread of execution beginning at the run() method. This causes the child thread's for loop to begin. After calling start(), NewThread 's constructor returns to main(). When the main thread resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish.

The output produced by this program is as follows: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting. Ref:ThreadRunnableApplication.java

Extending Thread The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that 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. Ref:ExtendThreadApplication.java

Extending thread class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: "+ this); start(); } 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("Child interrupted."); } System.out.println("Exiting child thread."); }

Extending thread continues.. 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."); }

Choosing an approach Thread class defines several methods that can be overridden by a derived class. Of these methods, the only one that must be overridden is run( ). Classes should be extended only when they are being enhanced or modified in some way. So, if you will not be overriding any of Thread's other methods, it is probably best simply to implement Runnable.

Creating Multiple Threads Refer : MultiThreadingApplication.java

class NewThread implements Runnable { String name; Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); } public void run() { try { 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."); } Creating Multiple Threads

class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } Multiple Threads continues..

Thread Priorities Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run A higher-priority thread can preempt a lower-priority one. When a lower-priority thread is running and a higher- priority thread resumes it will preempt the lower-priority thread. To set a thread's priority, use the setPriority() method, which is a member of Thread. final void setPriority(int level ) Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority,specify NORM_PRIORITY,which is currently 5.

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 called synchronization. Key to synchronization is the concept of the monitor (also called a semaphore ). 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 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. A thread that owns a monitor can reenter the same monitor if it so desires.

Using synchronized methods If different threads are trying to get single object the value of that object will mixed up.This condition is called racecondition If two or more threads access same method we can synchronize that by adding synchronized keyword While a thread is inside a synchronized method, all other threads that try to call it on the same instance have to wait. class Callme { synchronized void call(String msg) { ……………………………………………….. try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } ………………………………………………………………….. }

Sync Block 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(); } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block target.call(msg); }

If we are using a third party class that does not use synchronize method(source code is not available) use synchronized block synchronized(object) { // statements to be synchronized } object is a reference to the object being synchronized. Interthread Communication Assignment