Multithreading in java.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Threads CS Introduction to Operating Systems.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Java Programming: Advanced Topics
1 Java Threads Instructor: Mainak Chaudhuri
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.
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.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
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.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
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
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
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
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.
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.
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.
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
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
Multithreaded Programming in Java
Multithreading in Java
More About Threads.
Multithreading in Java
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.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
Multithreaded Programming
21 Threads.
Java Thread.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading in java

Overview Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.Java Multithreading is mostly used in games, animation etc. www.prolearninghub.com

Life Cycle of a Thread Runnable Running Waiting Dead New New Thread() Start run() Sleep(), wait() End of execution A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread. www.prolearninghub.com

Stages of the life cycle Following are the stages of the life cycle − New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as aborn thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. www.prolearninghub.com

Stages of the life cycle Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. www.prolearninghub.com

Stages of the life cycle Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates. www.prolearninghub.com

Creating a thread in Java There are two ways to create a thread in Java: By extending Thread class. By implementing Runnable interface. Method of thread class getName(): It is used for Obtaining 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(): Entry point for the thread sleep(): suspend a thread for a period of time start(): start a thread by calling its run() method www.prolearninghub.com

Thread creation by extending Thread class class MultithreadingDemo extends Thread{ public void run() { System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); obj.start(); Output My thread is in running state www.prolearninghub.com

implementing Runnable Interface Thread creation by implementing Runnable Interface class MultithreadingDemo implements Runnable{ public void run() { System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); Thread tobj =new Thread(obj); tobj.start(); Output My thread is in running state. www.prolearninghub.com

Example #1 public class Worker implements Runnable {   public static void main (String[] args)  {       System.out.println("This is currently running on the main thread, " +                "the id is: " + Thread.currentThread().getId());       Worker worker = new Worker();        Thread thread = new Thread(worker);       thread.start();   }     @Override     public void run()   {       System.out.println("This is currently running on a separate thread, " +               "the id is: " + Thread.currentThread().getId());     } }   www.prolearninghub.com

Output This is currently running on the main thread, the id is: 1 This is currently running on a separate thread, the id is: 9 www.prolearninghub.com

Thread Methods Following is the list of important methods available in the Thread class. Method Name Description public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. www.prolearninghub.com

Thread Methods Method Name Description public int getPriority() returns the priority of the thread. public String getName() returns the name of the thread. public Thread currentThread()  returns the reference of currently executing thread. public int getId() returns the id of the thread. public void resume() is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated). www.prolearninghub.com

Thread Syncronization When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file. www.prolearninghub.com

Thread Syncronization So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. www.prolearninghub.com

Thread Syncronization Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block. Following is the general form of the synchronized statement. Syntax synchronized(objectidentifier) { // Access shared variables and other shared resources } www.prolearninghub.com

Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent. www.prolearninghub.com