Multithreaded Programming in Java

Slides:



Advertisements
Similar presentations
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Java Programming: Advanced Topics
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
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)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Java Threads Representation and Management of Data on the Internet.
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.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
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.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 18 Advanced Java Concepts Threads and Multithreading.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading in JAVA
Scis.regis.edu ● CS-434: Object-Oriented Programming Using Java Week 8 Dr. Jesús Borrego Adjunct Faculty Regis University 1.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 More on Thread API.
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.
THREAD MODEL.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 4: Threads.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Chapter 4 – Thread Concepts
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Multithreading.
Chapter 4 – Thread Concepts
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Lecture 21 Concurrency Introduction
Multithreading in Java
Multithreading in Java
EE 422C Multithreading & Parallel Programming
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads Chapter 4.
21 Threads.
Multithreading in java.
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreaded Programming in Java Chapter 7 Multithreaded Programming in Java

Agenda Introduction to Threads Multitasking, Multithreading and Benefits Threads in Java Life cycle of a Thread States of Thread Creating Threads Thread Priorities Thread Synchronization Inter-thread Communication

Introduction to Threads “A java thread is an execution context or a lightweight process. It is a single sequential flow of control within a program. Java thread can be used to execute multiple tasks at the same time. “ Multitasking In computing, multitasking is a method by which multiple tasks, also known as processes, share common processing resources such as a CPU.

Introduction to Threads – Contd., Multitasking Process Based Multitasking Thread Based Multitasking

Introduction to Threads – Contd., Process Based Multitasking Is a Heavyweight process that runs in a different address space. so, context switch or intercommunication between processes is much expensive. Thread Based Multitasking Is a Light weight process and can run in a same address space so context switch or intercommunication between processes is less expensive. 

Introduction to Threads – Contd., A process that is made of one thread is known as single- threaded process. A process that creates two or more threads is called Multi-threaded process.

Multithreading “ Multithreading is the system environment where the tasks are sharing the same program under the multitasking environment. Multithreading is a subset of multitasking,since it concersn tasks which use the same program. Under the multithreading environment, a program is shared by several tasks concurrently. For each task, the program must work as if it were executing instructions exclusively for each task.”

Benefits of Multithreading Improved performance Minimized system resource usage Simultaneous access to multiple applications Program structure simplification

Threads in Java The java.lang.Thread class is used to construct and access individual threads in a multithreaded application. It provides a thread API and all the generic behavior for threads. These behaviors include starting, sleeping, running, yielding, and having a priority. Faculty Guide Lines Explain Thread model in Java Explain java.lang.Thread class and built-in methods in it. Demo on Main thread is given.

Threads in Java – Contd., Task of a Thread is defined in run() method: The run() method gives a thread something to do. Its code should implement the thread's running behavior. The first thread to be executed in a multithreaded process is called the main thread. The main thread is created automatically on the start up of Java program execution. Faculty Guide Lines Explain Thread model in Java Explain java.lang.Thread class and built-in methods in it. Demo on Main thread is given. MainThread.java

Life Cycle of a Thread The various states in the life cycle of a thread are: New Runnable Not Runnable Terminated or Dead

States of Thread New Runnable: Syntax: A thread object that is newly created. Syntax: Runnable: When the start method of thread is invoked, the JVM calls the run method. Now the thread is ready to execute but not allocated to the processor, because the processor may be busy with another operation. Thread newThread = new Thread(this,”threadName”);

States of Thread – Contd., Not Runnable: Sleep: When the sleep method of Thread class is called, the thread goes to the sleep state. When the time specified in the sleep method elapses, then the thread moves to runnable state. Wait: When the wait method is called, the thread goes to the wait state. It moves to runnable state when it is notified by another thread or time specified in the wait method elapses.

States of Thread – Contd., Blocked When a thread is waiting for any I/O operations, it transitions to the blocked state. When the required resource is available, then it moves to runnable state. Dead When the thread completes execution, it transitions to the dead state.

Creating Threads There are two ways to create thread in java: Implement the Runnable interface (java.lang.Runnable) By Extending the Thread class (java.lang.Thread) The Runnable Interface Signature public interface Runnable { void run(); }

Creating Threads – Contd., Extending Thread Class Public Class ThreadDemo extends Thread { Public void run() { //Task for thread defined. } }

Runnable Interface vs Thread Class When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class: Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option. A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be expensive. Runnable Interface Demo Extending ThreadClass Demo Creating MultipleThreads Demo

Thread Priorities In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. The following static final integer constants are defined in the Thread class: MIN_PRIORITY (0) Lowest Priority NORM_PRIORITY (5) Default Priority MAX_PRIORITY (10) Highest Priority

Thread Priorities – Contd., The priority of an individual thread can be set to any integer value between and including the above defined constants. Thread’s priority can be modified any time after its creation using the setPriority() method and its priority value can be retrieved using getPriority() method. When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution.

Thread Priorities – Contd., If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true: A higher priority thread becomes Runnable. (Pre-emptive scheduling) It yields, or its run() method exits on systems that support time- slicing, its time allotment has expired ThreadPriorityDemo Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms, as thread scheduling is host platform–dependent.

Thread Synchronization “ With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.” In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

Thread Synchronization – Contd., Synchronization is based on the concept of monitor. The monitor controls the way in which synchronized methods access an object or class. To enter an object’s monitor, you need to call a synchronized method or synchronized block. When a thread calls the wait() method, it temporarily releases the locks that it holds. In addition, the thread stops running and is added to the list of waiting threads for that object.

Thread Synchronization – Contd., Synchronization is achieved using synchronized key word Synchronization is achieved in two ways: Syncronized methods Synchronized blocks

Synchronized Methods “ Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. “ Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. A synchronized method can only use “this” current object.

Synchronized Methods – Contd., Example: public synchronized void add(int value) { this.count += value; } SynchronizationMethodDemo

SynchronizationBlockDemo Synchronized Blocks synchronized block you may lock on an object other than “this” which allows to be much more flexible. Example: public void add(int value){ Student s=new Student(); synchronized(s) { this.count += value; } SynchronizationBlockDemo

Inter-Thread Communication Communication between threads is known as Interthreaded communication. Java provides well designed inter-process mechanism using the wait(), notify() and notifyAll() methods. wait() tells the calling thread to exit and enter the ‘sleep’ state till some other thread enters and calls notify() public final void wait() throws InterruptedException public final notify() notifyAll() wakes up or notifies all the threads that called wait( Joining Threads: A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.

Wait-Notify Mechanism notify( ) wakes up or notifies the first thread. notify( )‏ First thread notifyAll( ) wakes up or notifies all the threads that called wait( ) on the same object. Thread 1 Thread 2 Thread 3 notifyAll( )‏ JoinDemo InterThreadCommDemo(Producer Consumer.java)

Summary A thread is defined as the path of execution of a program. It is a sequence of instructions that is executed to define a unique flow of control. A program that creates two or more threads is called a multithreaded program. The two types of multitasking are: Process-based Thread-based The java.lang.Thread class is used to construct and access individual threads in a multithreaded application.

Summary – Contd., The various advantages of multithreading are: Improved Performance Minimized System Resources Usage Simultaneous access to multiple applications The various states in the life cycle of a thread are: New Runnable Not Runnable Terminated or Dead You can create a thread in the following ways: Implementing Runnable interface Extending the Thread class

Summary – Contd., Thread priorities are the integers in the range of 1 to 10 that specify the priority of one thread with respect to the priority of another thread. You can set the thread priority after it is created using the setPriority() method declared in the Thread class. Synchronization of threads ensures that if two or more threads need to access a shared resource, the resource is used by only one thread at a time. Various threads can communicate with each other using the following methods: wait() notify() notifyAll()

References http://www.cs.bris.ac.uk/Teaching/Resources/MR09/lectures/mk2/img20.htm