Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.

Slides:



Advertisements
Similar presentations
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Advertisements

1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
1 Lecture 16 Introduction to Multithreading and Concurrency Overview  Introduction to Multithreading of Computation  Where are Threads used?  Why should.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
1 Java Threads Instructor: Mainak Chaudhuri
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
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.
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.
Internet Software Development Controlling Threads Paul J Krause.
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.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
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
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
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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.
Java 3: Odds & Ends Advanced Programming Techniques.
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.
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.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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 (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
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.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Java Based Techhnology
Multithreading.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads in Java

2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without any difficulty. Objective: After completing this chapter you will able to know, Introduction What is a Thread Where to use Threads Where to use Single Threads Associating a method with Thread Declare a subclass of Thread that defines the run() method Pass a reference to an object that implements the Runnable interface to a Thread constructor Starting a Thread Controlling a Thread

3 Interrupted Exception and Thread Priority Controlling Group of Threads and Synchronizing Multiple Threads Single Threaded Execution Optimistic Single Threaded Execution Locking an Object Deadlock and volatile keyword 7.0 Threads

4 Introduction What is a Thread ? Flow of Control in a Program Similar to a process but multiple threads can share same state. All threads in an application run in the same address space. Share all resources except Stack. –In Java “thread” means two different things : An Instance of java.lang.Thread –An Instance of Thread is an Object - similar to any other object in java A Thread of execution –Is an individual process that has its own call stack

5 Introduction Where to use Threads ? Where there is a need to engage multiple activities and still be able to respond to additional input from the user. E.g.: A web browser should be able to respond to user input while fetching an image or playing a sound. Where to use Single Threads? Programs that requires sequential logic

6 Associating a method with a Thread Java provides two ways of associating a method with a Thread : Declare a subclass of Thread that defines the run() method. Pass a reference to an object that implements the Runnable interface to a Thread constructor. Declare a subclass of Thread that defines the run() method : Subclassing - convenient when the method you want to run in a thread does not need to belong to a particular class. E.g. : If you need to load the contents of a URL as part of an applet’s initialization,but the applet can provide other functionality before the content is loaded, you might want to load the content in a separate thread. The class that does it is :

7 Associating a method with a Thread E.g : class UrlData extends Thread { private Object data; private URL url; public UrlData(String urlName)throws MalformedURLException { url = new URL(urlName); start(); } public void run() { try { data = url.getContent(); } catch (java.io.IOException e) { } public Object getUrlData(){ return data; }

8 Associating a method with a Thread Pass a reference to an object that implements the Runnable interface to a Thread constructor : –The method that you want to run in a thread to be a part of a particular class that is a subclass of a class other than thread, then use the runnable interface. E.g.: class AutoColor extends java.awt.Canvas implements Runnable { private Thread myThread; AutoColorChange () { myThread = new Thread(this); myThread.start();... } public void run() {... }

9 Starting a Thread main Method1 main run public static void main(String args[]) { //running //some code //in main()‏ method1(); //running //more code } void method1() { Runnable r = new Runnable(); Thread t = new Thread(); t.start(); //do more stuff } method1 main 1) main() begins 2) main() invokes method1()‏ 3) method1() starts a new thread Stack A Stack B

10 Controlling a Thread Starting a Thread – use the start() method. isAlive() method of the Thread Object – always returns false before starting a thread. After start() method has returned – isAlive() method always returns true. note : On a multi processor system the start() method can even return at the same time the started thread begins to run. Thread Objects have parent child relationship. A Thread dies when one of the following things happens: The run() method called by Thread returns. An Exception is thrown that causes the run() method to be exited. The stop() method of the thread is called.

11 Controlling a Thread NewRunnable Running Dead Waiting/ Blocking TRANSITION BETWEEN THREAD STATES

12 Interrupted Exception and Thread Priority Interrupted Exception : Methods in Java API such as wait(), join() »throws an Interrupted Exception. »These methods temporarily suspend the execution of a thread. Thread Priority : getPriority() – helps to query the priority of the a Thread Object setPriority() – helps to set the priority of a Thread. Priorities are set using positive integers – usually between 1 to 10 ( however they’re not guaranteed)‏ Default Priority – 5 Thread class has 3 constants that define the range of priorities : Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10) Note : It is possible for the current priority of the Thread to be greater than the maximum allowable priority for the Thread Group.

13 Controlling Group of Threads & Synchronizing Multiple Threads ThreadGroup class: –Every Thread object belongs to the ThreadGroup object. Synchronizing Multiple Threads : –Correct behavior of a multi threaded program generally depends on multiple threads cooperating with each other – achieved through synchronization. –Simplest strategy for ensuring that threads are correctly synchronized : Write a code that works correctly when executed concurrently by any number of threads.

14 Single Threaded Execution E.g.: class CountIt { int i = 0; void count() { i = i + 1; } In the above method if 2 threads A and B, calls count in the same time then the problem arises. Modified program : class CountIt { int i = 0; synchronized void count() { i = i + 1; } So by making the method synchronized, avoids the problem in the former code.

15 Single Threaded Execution The strategy of single threaded execution can also be used when multiple method update the same data. E.g.: class CountIt2 { int i = 0; void count() { i = i + 1; } void count2() { i = i + 2; } –In the above example the result could be to increment i by 1,2 or 3. –To avert the problem with the above code - declare both methods as synchronized.

16 Single Threaded Execution By just making a method synchronized does not provide the needed single threaded execution in situations like: –When an inner class is updating fields in its enclosing instance. E.g.: public class Z extends Frame { int pressCount = 0;... private class CountButton extends Button implements Action Listener { public void actionPerformed(ActionEvent evt) { pressCount ++; }... }

17 Single Threaded Execution In this former case –By just declaring the actionPerformed() method as synchronized only forces the method to acquire lock on the instance of CountButton it is associated with it. –But the needed is to acquire a lock for is the enclosing instance of Z. Robust approach is to have the inner class update a field in its enclosing instance by calling a synchronized method in the enclosing instance

18 Single Threaded Execution public class Z extends Frame { int pressCount = 0; synchronized incrementPressCount() { pressCount++; }... private class CountButton extends Button implements ActionListener { public void actionPerformed(ActionEvent evt) { incrementPressCount(); }... }

19 Optimistic Single Threaded Execution Similar to Single Threaded Execution strategy. Both of them : –begins by getting a lock on an object. –Ends by releasing the lock on that object. –The Difference happens in between : If a piece of code discovers that conditions are not right to proceed, the code releases the lock it has on the object and waits. After another piece of code makes things right, it notifies the first piece of code to proceed. The first piece of code now try to regain its lock on the object and continue. To implement this the Object class provides the following methods: wait()‏ Notify()‏ notifyAll()‏

20 Optimistic Single Threaded Execution Consider the following example : – It shows how to implement a queue that uses optimistic single threaded execution strategy. E.g : public class Queue extends java.util.Vector { synchronized public void put(Object obj) { addElement(obj); notify(); } synchronized public Object get() throws EmptyQueueException { while (size() == 0) wait(); Object obj = elementAt(0); removeElementAt(0); return obj; }

21 Locking an Object critical sections : –Code segments that access the same object from separate concurrent threads. Example : public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() {... } public synchronized void put(int value) {... } –In the above example : Both methods put() and get() has synchronized keyword. If the control enters a synchronized method : –method locks the object and now other threads will not be able to call any other method in same the object, until the object is unlocked. –The acquisition and release of lock is done automatically by the JVM.

22 Locking an Object Reacquiring a lock : –Java locks are reentrant. –Reentrant locks – eliminates the possibility of a single thread deadlocking itself on a lock that it already holds. E.g.: public class Reentrant { public synchronized void a() { b(); System.out.println("here I am, in a()"); } public synchronized void b() { System.out.println("here I am, in b()"); } On calling method a() the Output is : here I am, in b() here I am, in a() –The above output was possible as java supports reentrant locks. –Suppose if reentrant locks were not supported, this code would have caused a deadlock state.

23 Locking an Object Using the notifyAll and wait methods: E.g : public synchronized int get() { while (available == false) { try { // wait for Producer to put value wait(); } catch (InterruptedException e) { } available = false; // notify Producer that value has been retrieved notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { // wait for Consumer to get value wait(); } catch (InterruptedException e) { } } contents = value; available = true; // notify Consumer that value has been set notifyAll(); }

24 Deadlock and Volatile Keyword Deadlock : –Occurs when two threads are blocked, each waiting for the other’s lock. Volatile Keyword : –Informs the compiler that several threads may be accessing this simultaneously.

25 Threads - Summary Java is fundamentally multi-threaded. Every thread corresponds to an instance of java.lang.Thread class or a sub-class. A thread becomes eligible to run, when its start() method is called. Thread scheduler co- ordinates between the threads and allows them to run. When a thread begins execution, the scheduler calls its run method. Signature of run method – public void run()‏ When a thread returns from its run method (or stop method is called – deprecated in 1.2), its dead. It cannot be restarted, but its methods can be called. (it’s just an object no more in a running state)‏ There are two ways to implement threads. 1. Extend Thread class 2. Implement Runnable interface Threads have priorities. Thread class have constants MAX_PRIORITY (10),MIN_PRIORITY (1),NORM_PRIORITY (5)‏

26 Threads - Summary Every object has a lock (for every synchronized code block). At any moment, this lock is controlled by at most one thread. A thread that wants to execute an object’s synchronized code must acquire the lock of the object.If it cannot acquire the lock, the thread goes into blocked state and comes to ready only when the object’s lock is available. When a thread, which owns a lock, finishes executing the synchronized code, it gives up the lock. 2 ways to synchronize: –Synchronize the entire method –Synchronize part of the method

27 Test Your Understanding What is a Thread? What for is a Thread used? What is Multi-Threading? What is a lock on object? What for is an object locked by a thread?