Multithreading.

Slides:



Advertisements
Similar presentations
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
Advertisements

Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Practice Session 7 Synchronization Liveness Guarded Methods Model
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Multithreading A thread is the flow of execution, from beginning to end, of a task in a program. With Java, you can launch multiple threads from a program.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
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.
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.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Static Keyword. What is static The static keyword is used when a member variable of a class has to be shared between all the instances of the class. All.
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)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Computer Engineering Rabie A. Ramadan Lecture 8. Agenda 2 Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing.
1 Web Based Programming Section 8 James King 12 August 2003.
Threading Eriq Muhammad Adams J
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
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.
Multi-Threading in Java
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Multithreading and Garbage Collection Session 16.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
Doing Several Things at Once
Multi Threading.
Java Multithreading.
Multithreading.
PA1 Discussion.
Multithreaded Programming in Java
Java Concurrency.
Multithreading in Java
Threads Chate Patanothai.
Java Concurrency.
Distributed Systems - Comp 655
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Java Thread.
Threads and Multithreading
Parallel programming in Java
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading

Threads Threads are lightweight processes as the overhead of switching between threads is less The can be easily spawned The Java Virtual Machine spawns a thread when your program is run called the Main Thread

Why do we need threads? To enhance parallel processing To increase response to the user To utilize the idle time of the CPU Prioritize your work depending on priority

Example Consider a simple web server The web server listens for request and serves it If the web server was not multithreaded, the requests processing would be in a queue, thus increasing the response time and also might hang the server if there was a bad request. By implementing in a multithreaded environment, the web server can serve multiple request simultaneously thus improving response time

Creating threads In java threads can be created by extending the Thread class or implementing the Runnable Interface It is more preferred to implement the Runnable Interface so that we can extend properties from other classes Implement the run() method which is the starting point for thread execution

Running threads Example class mythread implements Runnable{ public void run(){ System.out.println(“Thread Started”); } class mainclass { public static void main(String args[]){ Thread t = new Thread(new mythread()); // This is the way to instantiate a thread implementing runnable interface t.start(); // starts the thread by running the run method Calling t.run() does not start a thread, it is just a simple method call. Creating an object does not create a thread, calling start() method creates the thread.

Synchronization Synchronization is prevent data corruption Synchronization allows only one thread to perform an operation on a object at a time. If multiple threads require an access to an object, synchronization helps in maintaining consistency.

Example public class Counter{ private int count = 0; public int getCount(){   return count; } public setCount(int count){    this.count = count; In this example, the counter tells how many an access has been made. If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count.

Fixing the example public class Counter{ private static int count = 0; public synchronized int getCount(){   return count; } public synchoronized setCount(int count){    this.count = count; By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state. The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads.

What about static methods? public class Counter{ private int count = 0; public static synchronized int getCount(){   return count; } public static synchronized setCount(int count){    this.count = count; In this example the methods are static and hence are associated with the class object and not the instance. Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static synchronized methods are still available for access by other threads.

Common Synchronization mistake public class Counter{ private int count = 0; public static synchronized int getCount(){   return count; } public synchronized setCount(int count){    this.count = count; The common mistake here is one method is static synchronized and another method is non static synchronized. This makes a difference as locks are placed on two different objects. The class object and the instance and hence two different threads can access the methods simultaneously.

Object locking The object can be explicitly locked in this way synchronized(myInstance){ try{ wait(); }catch(InterruptedException ex){ } System.out.println(“Iam in this “); notifyAll(); The synchronized keyword locks the object. The wait keyword waits for the lock to be acquired, if the object was already locked by another thread. Notifyall() notifies other threads that the lock is about to be released by the current thread. Another method notify() is available for use, which wakes up only the next thread which is in queue for the object, notifyall() wakes up all the threads and transfers the lock to another thread having the highest priority.

Further Reading http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html