Object Oriented Programming (II-Year CSE II-Sem-R09)

Similar documents
Unit - IV Multi-Threading

7. MULTITHREDED PROGRAMMING

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Module - 4 Multi-Threaded Programming

Concurrent Programming using Threads

Unit III Rupali Sherekar 2017

Multithread Computing

CS 556 Distributed Systems

Contents. 6-1 Copyright (c) N. Afshartous

CIS233J Java Programming II. Threads

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multithreaded Programming

Object Oriented Programming. Week 10 Part 1 Threads

Amity School of Engineering

Software Practice 1 - Multithreading

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Threads Chate Patanothai

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Introduction to Java Threads

Threads Questions Important Questions

CMSC 132: Object-Oriented Programming II. Threads in Java

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

By: Abhishek Khare (SVIM - INDORE M.P)

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Multithreading Pearson Education, Inc. All rights reserved.

Unit 5 - Exception Handling & Multithreaded

04-Java Multithreading

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

JAVA - MULTITHREADING

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Animation Part 2: MoveableShape interface & Multithreading

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Multithreaded Programming

Chapter 32 Multithreading and Parallel Programming

Chapter 19 Multithreading

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Java s Implementation of Concurrency, and how to use it in our applications.

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Threads in Java (Deitel & Deitel)

Performance Throughput Utilization of system resources

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

JAVA. Lab 12 & 13: Multithreading

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Java Threads. Written by John Bell for CS 342, Spring 2018

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Advanced Concepts of Programming

Multi-threading in Java. Jeff HUANG

Concurrent Computing CSCI 201 Principles of Software Development

public class Shared0 { private static int x = 0, y = 0;

MULTI-THREADING

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Java Threads. Introduction to Java Threads

Synchronization

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Advanced Programming Concurrency

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CS360 Lecture 12 Multithreading

UNIT V CONCURRENT PROGRAMMING

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Programming Language Concepts: Lecture 11

Java Threads. COMP 585 Noteset #2 1

Definition: A thread is a single sequential flow of control within a program.

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Object-Oriented Programming Concepts-15CS45

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Techniques of Java Programming: Concurrent Programming in Java

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Multithreading using Java. Dr. Ferdin Joe John Joseph

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Programming Java. Multithreaded Programming

What is a thread anyway?

EDAF65 Processes and Threads

Basics of. Multithreading in Java

CERTIFICATION OBJECTIVES

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

EDA095 Processes and Threads

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Concurrent Programming

Threads. What Is a Thread? Customizing a Thread's run Method. Understanding Threads. Subclassing Thread and Overriding run. Thread Objects.

CS342: Software Design. November 21, 2017

CMSC 330: Organization of Programming Languages

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Synchronization synchronization.

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 11, 2007 Objectives


DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Threads and Parallelism in Java

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Transcription:

(II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad)

Multithreading A thread is a single sequential (separate) flow of control within program. Sometimes, it is called an execution context or a light weight process. A thread itself is not a program, A thread cannot run on its own. Rather, it runs within a program. A program can be divided into a number of packets of code---- each representing a thread having its own separate flow of control. That is, a thread can t exist by itself. It is a part of program. Light Weight process: A thread is considered a light weight process because it runs within the context of program (within the program) and takes the advantage of the resources allocated to that program. Heavy weight process: In the heavy weight process, the control changes in between threads belonging to different processes (i.e. two different programs). (In light weight process, the control changes in between threads belonging to same (one) process. Execution context: A thread will have its own execution stack and program counter. The code running within the thread works only within that context. Package support for threads: Java.lang.thread: In java Language, threads are objects that derive from java.lang.thread class. We can subclass the thread class to get functionality of the thread. Thread is a concrete class. Java.lang.Runnable: Runnable is an interface which provides an abstract method run() for a thread. Java.lang.object: This is the root class for every class and defines the three methods for use of threads. The methods are wait(), notify() and notifyall(). Java language has two keywords related to threads: volatile and synchronized. Both of these keywords help ensure the integrity of data that is shared between two concurrently running threads. run() method: The run() method is available both in thread class and Runnable interface. We can subclass a Thread class and override the run(0 method. We write the specific code, which we would like to do by the thread, in the run() method. run() method is the heart of any Thread. run( ) method is called implicitly by the start() method. In java, we can create threads in two ways --- one by sub classing the Thread class and one by implementing Runnable interface. A program by sub classing the thread class 1

We can create threads by extending Thread class to our class. In the following program, the class Using Thread extends the class Thread. By this every object of class Using thread becomes implicitly a thread (i.e it can utilize all the methods of thread class). Ex: printing 10 no s using a thread. Thread class is extended Filename: UsingThread.java public class UsingThread extends Thread // Thread class is extended public void run() //write the code specific to the thread in run() method try for(int i=1;i<11;i++) S.o.p( Hello +i); //prints hello 10 times Thread.sleep(1000);//with a gap pf 1000 milliseconds //sleep() is a static method of Thread class //which makes a thread to sleep9not functioning) for the specific time Catch(InterruptedException e) e.printstacktrace(); S.o.p( Done ); //when run s job is over Done is printed public static void main(string args[]) UsingThread ut=new UsingThread(); ut.start(); //athread starts its functioning with start() method only The run() method of UsingThread class overrides the empty run(0 method of Thread class with a for loop that iterates 10 times. Between each iteration it sleeps for 1 second(1000 ms). After the loop has finished it prints Done. About sleep() method Sleep() is a method of Thread class with the following signature: public static void sleep (long milliseconds) throws InterruptedException sleep() method is static and throws (claims) a checked exception interrupted exception. That is when ever we use, sleep() method, we should take care of InterruptedException by providing try- catch block. sleep() method makes a running (active) thread not to run(inactive) for the specified milliseconds of time. When the sleep time expires, the thread becomes automatically active. The active thread executes the run() method code. When the thread comes out of the run() method, it dies (naturally,the work assigned to it is over. That is why, we write the code that is to be done by thread in run() method). About start() method UsingThread ut = new UsingThread(); ut.start(); In the above first statement, a thread by name ut is created (ut is actually an object of UsingThread class, but becomes implicitly a thread as the class has extended Thread class). 2

The thread ut is in born state and is inactive. The inactive thread cannot call run() method. The thread in born state occupies the memory resources but cannot take microprocessor time. In the second statement, we call the start() method on the thread. Start() method implicitly calls run() method. The thread in run state is active and utilizes microprocessor time. A program by implementing Runnable interface The above program is rewritten by implementing Runnable interface (instead of extending thread class). Everything is same but for the small difference of writing implements instead of extends. Another difference is that the run() method in Thread class is a concrete method andit is left to the subclass to override it or not (anyhow, we will override). The same ru() method in Runnable interface is an abstract method. that is, the subclass that implements the Runnable interface must override the run() method. Example: Printing 10 numbers by using Runnable interface. Filename:UsingRunnable.java Public class UsingRunnable implements Runnable public void run(0 try for(int i=1;i<111;i++) System.out.println( Hello +i); Thread.sleep(1000); catch(interruptedexception e) e.printstacktrace(); System.out.println( Done ); public static void main(string args[]) UsingRunnable ur=new UsingRunnable(); Thread t = new Thread(ur); //this line is extra than previous program t.start(); We cannot call ur.start(0) directly and if called raises a compilation error. This is because the object ur (or the class UsingRunnable) is no way connected to the start(0 method of Thread class. To overcome this,java designers provided a way of passing ur as an argument to the Thread constructor. t.start() implicitly calls the run() method of UsingRunnable class. Instance of UsingRunnable class is passed as a parameter to the Thread constructor. And instead of starting the object ur,object of Thread class, t is started. This is the difference between the above two programs. Using Multiple threads we can execute different threads concurrently (and is the purpose of a multithreaded program). The source code includes three individual programs-first Thread, Second Thread and TwoRuns. FirstThread and SecondThread classes extend Thread class. The objects of these classes are created and their start(0 methods are called from Two runs class. Example: to execute two run methods and observe outputs with different sleep periods. File Name: TwoRuns.java class FirstThread extends thread public void run() 3

for(int i=1;i<5;i++) System.out.println( First thread: +i); Try Thread.sleep(1000); catch(interruptedexception e) e.printstacktrace(); class SecondThread extends Thread public void run() for(int i=1;i<5;i++) System.out.println( SecondTthread: +i); try Thread.sleep(1000); catch(interruptedexception e) e.printstacktrace(); public class TwoRuns public static void main(string args[]) FirstThread ft=new FirstThread(); //create the objects of the classes SecondThread st=new SecondThread();//each object is a thread implicitly ft.start();//start the threads st.start();//there is no shortcut to start both the threads at a time try ft.join(); st.join(); //join method throws InterruptedException catch(interruptedexception e) e.printstacktrace(); Output: FirstThread 1 SecondThread 1 FirstThread 2 SecondThread 2 FirstThread 3 Second Thread 3 First Thread 4 Second Thread 4 Note: Change the sleep timings of both the run methods and observe the outputs frequency. After running the above program, keep try-catch block of join() methods in comments, and see the difference in output (order of execution). Thread Scheduler 4

In TwoRuns class, we created and started two threads- ft and st. Now both are eligible for microprocessor time. As the sleep method values are same, each thread is executed alternatively. If the sleep timings are changed we get different outputs. Allocation of microprocessor time for all the threads is controlled by Thread Scheduler, managed by the operating system. For allocation of microprocessor time, thread scheduler takes into consideration many factors like a) the waiting period of thread b) the priority of thread etc. If a thread is in inactive state(like in sleep() method), thread scheduler keeps it away(from the pool of threads). When the inactive state is over, the thread joins the pool of threads waiting for Microprocessor time. The thread scheduler manages the pool of threads. Algorithm of thread scheduler is operating system dependent. Different operating systems adopt different algorithms. Thread scheduler allocates the processor time first to higher priority threads. To allocate microprocessor time in between the threads of the same priority, thread scheduler follows round robin fashion. Join(): used for the caller s thread to wait for this thread to die---for example, by coming to the end of the run() method. Lifecycle of thread: Just like applets and servlets threads too got a lifecycle between their birth (thread object creation) and death (thread object garbage collection). Lifecycle constitutes different stages a thread can undergo in its life (existence). When to subclass the Thread or when to implement Runnable: If ur class is already extending anyclass(e.g. Applet or Frame), the choice left to u is implementing runnable interface. Otherwise ur left with any choice At any time,a thread is said to be in one of the several states. Bornstate: A thread is just created(but not started),is in born state.the thread remains in this state until the thread s start() method is called;this causes the thread to enter the ready state. A thread in ready state is eligible to utilize microprocessor time. A thread enter the dead state When its run() method completes or when its stop method is called. A dead thread cannot enter again the run state as it is garbage collected. When running thread s sleep method is called, that thread enters the sleeping state. A sleeping thread enters the ready state again when the sleep time expires. A sleeping thread cannot use microprocessor time, even if the microprocessor is idle. When on a running thread, if suspend() method is called, the thread enters suspended state. A suspended thread becomes ready with resume() method. A suspended thread cannot use processor time, even if it is available. 5

When on running thread,if wait() method is called, the thread enters a waiting state where it will be waiting in queue of threads (used in synchronization). The thread comes into ready state when notify() is issued on the thread by another thread. A thread enters the dead state when its run method completes or stop() method is called. The stop() method sends a ThreadDeath object to the thread. ThreadDeath is a subclass of class Error. Making a thread Not Runnable: A thread becomes not runnable when one of these events occur: Its sleep method is called The thread calls the wait method to wait for as specific condition to be satisfied The thread is blocked by an I/O operation. When power fails (ofcourse,system itself stops). After knowing something about threads, its high time to study the Thread class & thread related classes & their methods. Thread class The Thread class is included in java.lang package, a package that is implicitly imported into every program. The super class of Thread is object class. Thread class play a vital role in Java s multithreading. Just like any other Java class, the Thread class is rich with its methods having different functionality. Following is the class signature: public class Thread extends Object implements Runnable Constructors Description public Thread() creates a thread with default name public Thread(String name) create a thread with name Public Thread(ThreadGroup group, String name) creates a thread in a thread group with name Fields when to use public final static int MIN_PRIORITY=1 to associate a thread with minimum priority public final static int NORM_PRIORITY=5 to associate a thread with normal priority public final static int MAX_PRIORITY=10 to associate a thread with maximum priority Methods what they give public static native Thread current Thread() returns the current thread being executed on the microprocessor public static native void sleep (long millisecs) keeps thread in blocked state throws Interrupted Exception Methods what they give public final void join() throws Interrupted Exception waits until the target thread terminates public static void native yield() yield a waiting thread public final String get Name() returns the name of the thread public final void setname(string name) sets a name to the thread public final ThreadGroup getthreadgroup() returns the threads group to which it belong Public final native boolean isalive() returns true if a thread is alive else false if dead public final boolean isdaemon() checks whether a thread is daemon or not Public boolean isinterrupted() returns true if thread is Interrupted public void run() by default run method is called public final void setdaemon(boolean on) makes a thread daemon if true public final int getpriority() returns the priority of the thread public final void setpriority(int priority) sets the priority to thread public synchronized native void start() starts a thread 6

public final void stop() public final void suspend() Public final void resume() stops a thread and when stopped garbagecollected to suspend a thread to resume a thread when suspended isalive() method: The isalive() method returns true if the thread has been started and not stopped. If the isalive() method returns false, the thread is either in the born (not started still with start()) state or dead state. If the isalive()method returns true, it means the thread is in either Runnable State or not Runnable (blocked state) state. Daemon Threads: A daemon thread is a thread that runs for the benefit of threads. Daemon threads are known as service threads. Daemon threads run in the background and come into execution when the microprocessor is idle. The garbage collector is an example for a daemon thread. We can set a thread to be daemon one, by calling the thread setdaemon(true0. If the parameter is false, thread is not a daemon thread, the default one. A thread must be set to daemon, if wanted, before it starts(i.e,start() is called). Example:using different methods of Thread class FileName:ThreadMethodsDemo.java public class ThreadMethodsDemo extends Thread psvm(string args[]) Thread t1=new Thread(); //create a thread object of Thread class S.o.p( Default t1 Name: +t1.getname()); //prints Thread-0 t1.setname( Hello Thread ); System.out.println( t1 Name after assigning: +t1.getname()); //Hello Thread s.o.p( Default priority of t1: +t1.getpriority()); //prints 5 t1.setpriority(thread.max_priority); //setting a priority to a thread s.o.p( priority of t1 after setting: +t1.getpriority()); //prints 10 s.o.p( Default thread group of t1: +t1.getthreadgroup());//prints main System.out.println( Default t1 is Daemon(): +t1.isdaemon()); //false t1.setdaemon(true); //making a thread as a daemon thread S.o.p( after setting t1 is daemon(): +t1.isdaemon()); //true System.out.println( ti.isalive(): +t1.isalive()); //prints false as start() is not called still S.o.p( t1.isinterrupted(): +t1.isinterrupted()); getthreadgroup(): getthreadgroup() of Thread class returns the name of the thread group for which the thread belongs. Every thread should belong to a thread group (like a file does not exist without a Directory). If no group is specified by the programmer to a thread, by default,it is placed in main group. main is a group name and also a thread name. the default priority of main is 5. Thread priority The order of execution of multiple threads on a single cpu, depends on the scheduling. The java runtime supports a scheduling algorithm called fixed priority scheduling.the algorithm schedules the threads based on their priority relative to each other Runnable threads. Every java thread has a priority in the range Thread.MIN_PRIORITY(of constant 1) and Thread.MAX_PRIORITY(of constant 10). By default, each thread is given a priority of Thread.NORM_PRIORITY(of constant 5). Each new thread inherits the priority of thread 7

that creates it. The job of thread scheduler is to keep the highest-priority thread running all the time and for the threads of same priority, time slices are allocated in round-robin fashion. A threads priority can be adjusted with setpriority() method. Thread Group Every thread belongs to some group. That is no thread exists without a group (like no file exists without a directory). While creating a thread, if no group is specified, by default it is put into main thread group. A thread group can have both threads and other thread groups as members (like a directory can have both directories and files). The following is the signature of the ThreadGroup class: public class ThreadGroup extends Object resume() and suspend() suspend() method is used to temporarily stop the execution (making inactive) of the thread. All the resources of the thread are retained (not destroyed). Resume() is a method which can start a suspended thread (and making it active again). Synchronization: The examples so far u have practiced are independent and asynchronous. Each thread contained all the data and methods required for its execution and did not require any outside resources or methods. But is not the case always. There may be situations when threads share same data and must consider the activities of other threads. It is necessary to carefully coordinate the actions between threads especially when access the same data. Data corruption can occur if a multi threaded program is not designed correctly. The data used by many threads is often referred to as critical section data. A thread that plays nicely with the other threads and does not try to mess with a critical section while another thread is using it is referred to as thread safe. As an example consider the following example of bank account that is shared by multiple consumers (joint account of 10 partners). Each of these customers can make deposits to or withdrawals from this account. The following figure depicts one possible scheduling of these threads. At time t0, the balance is 0. The thread wants to deposit Rs.10 to the account. The current value of the account is read at time t1. however a context switch from Thread A to Thread B occurs at time t2. Thread B then reads the value of the account at time t3. It increments this value by Rs.10 at the time t4. Another context switch occurs at time t5. this returns control to Thread A. At time t6, it sets the account balance to Rs. 10. The net effect of this sequencing is that the final account balance is only Rs. 10 instead of 20. This is due to data corruption. The solution to this problem is to synchronize the access to this common (shared) data (balance). This can be done by synchronizing the method. When a thread begins executing a synchronized method, it automatically acquires a lock on that object. The lock automatically relinquished when the method completes. Only one thread may have this lock at any time. If the second thread tries to access the synchronized method when already being executed, the JVM causes the second thread to wait until the first thread relinquishes (leaves) the lock. 8

Deadlock Deadlock is an error that can be encountered in multithreaded programs. It occurs when two or more threads wait indefinitely for each other to obtain locks. Assume that a thread1 holds a lock on object1 and waits for a lock on object2. Similarly, thread2 hilds a lock onobject2 and waits for lock on object1. Neither of these threads may proceed. Each waits for ever for the other to obtain the lock it needs. Using synchronized keyword to deadlock the objects. wait, notify, and notifyall(): The wait() method can be used to suspend a thread until an objects monitor changes status. It must be used inside a method or block of code that is synchronized. It operates by releasing the monitor and putting the current thread to sleep until some other thread calls notify() or notifyall() on the synchronized object. Other threads can enter the synchronized method (or block) once wait has been called. 9