Multithreading.

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

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Definitions Process – An executing program
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.
Java Programming: Advanced Topics
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
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.
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.
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.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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
Java Thread and Memory Model
Threading and Concurrency COM379T John Murray –
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.
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.
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.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
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
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
Multithreading in Java
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Exception Handling Visit for more Learning Resources.
Multithreading.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreaded Programming
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
21 Threads.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading

Introduction The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximize the CPU time utilization. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program is called thread.

Thread A thread is a light-weight smallest part of a process that can run concurrently with the other parts(other threads) of the same process.  Thread is similar to a program that has single flow of control. Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life Cycle of a Thread

Newborn state: When a thread object is created it is said to be in a new born state. When the thread is in a new born state it is not scheduled running from this state. It can be scheduled for running by start() method or killed by stop() method. If it is put in a queue it moves to runnable state.

2. Runnable State: It means that thread is ready for execution and is waiting in queue for the availability of the processor. If all threads have equal priority then they are given time slots for execution in round robin fashion. The thread that relinquishes control joins the queue at the end and again waits for its turn. A thread can relinquish the control to another thread before its turn comes by yield().

3. Running State: It means that the processor has given its time to the thread for execution. The thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.

4. Blocked state: A thread can be temporarily suspended or blocked from entering into the runnable and running state by using either of the following thread method. Suspend() : Thread can be suspended by this method. It can be rescheduled by resume(). Wait() : If a thread requires to wait until some event occurs, it can be done using wait() method and can be scheduled to run again by notify(). Sleep() : We can put a thread to sleep for a specified time period using sleep(time) where time is in milliseconds. It re-enters the runnable state as soon as period has elapsed /over

5. Dead State: Whenever we want to stop a thread form running further we can call its stop(). This method causes the thread to move to a dead state. A thread will also move to dead state automatically when it reaches to end of the method. The stop() method may be used when the premature death is required.

Creating a thread Java defines two ways by which a thread can be created. By implementing the Runnable interface. By extending the Thread class.

Implementing the Runnable Interface Create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form, public void run();

Example class MyThread implements Runnable { public void run() System.out.println("concurrent thread started running.."); } class MyThreadDemo public static void main( String args[] ) MyThread mt = new MyThread(); Thread t = new Thread(mt); t.start(); Output : concurrent thread started running..

Extending Thread class This is another way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.

Example class MyThread extends Thread { public void run() System.out.println("Concurrent thread started running.."); } classMyThreadDemo public static void main( String args[] ) MyThread mt = new MyThread(); mt.start(); Output : concurrent thread started running..

Thread Priority Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as pre-emptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

Thread Priority 3 constants defiend in Thread class: public static int MIN_PRIORITY public static int NORM_PRIORITY public static int MAX_PRIORITY The value of Default priority i.e. NORM_PRIORITY is 5. The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Thread Priority Methods To set a thread's priority, use the setPriority() method, which is a member of Thread. This is its general form: final void setPriority(int level) You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here: final int getPriority( )

Example of priority of a Thread class TestMultiPriority extends Thread { public void run() System.out.println("running thread name is:” + Thread.currentThread().getName()); System.out.println("running thread priority is:” + Thread.currentThread().getPriority()); } public static void main(String args[]) { TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } }

Synchronization At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronized keyword in java creates a block of code referred to as critical section.

General Syntax : synchronized (object) { //statement to be synchronized } Every Java object with a critical section of code gets a lock associated with the object. To enter critical section a thread need to obtain the corresponding object's lock.

Need of Synchronization If we do not use synchronization, and let two or more threads access a shared resource at the same time, it will lead to distorted results. For example, Suppose we have two different threads T1 and T2, T1 starts execution and save certain values in a file temporary.txt which will be used to calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result. To prevent such problems, synchronization was introduced. With synchronization in above case, once T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread will be able to access or modify it until T1 returns.

When we declare a method synchronized, Java creates a “monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock. Whenever a thread has completed its work of using synchronized method, it will hand over the monitor to the next thread that is ready to use the same resource.

Deadlock Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

Inter-thread communication Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class: wait() notify() notifyAll()

1) wait() method 2) notify() method 3) notifyAll() method Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. 2) notify() method Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. 3) notifyAll() method Wakes up all threads that are waiting on this object's monitor. 

Thread Exceptions The call to sleep() method is in a try block and followed by a catch block. Because the sleep() method throws an exception, which should be caught otherwise program will not compile. Java runtime system will throw an IllegalThreadStateException whenever we attempt to invoke a method that a thread cannot handle in the given state. E.g. a sleeping thread cannot deal with the resume() method because a sleeping thread cannot receive any instructions. Similarly we cannot use suspend() method on a blocked thread.