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

Similar documents
Unit 5 - Exception Handling & Multithreaded

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Amity School of Engineering

CIS233J Java Programming II. Threads

Unit - IV Multi-Threading

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Multithreaded Programming

7. MULTITHREDED PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Unit III Rupali Sherekar 2017

Multithreading using Java. Dr. Ferdin Joe John Joseph

CS 556 Distributed Systems

Here is a hierarchy of classes to deal with Input and Output streams.

JAVA. Lab 12 & 13: Multithreading

Object Oriented Programming. Week 10 Part 1 Threads

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

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

Software Practice 1 - Multithreading

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

Software Practice 1 - Error Handling

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

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

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

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

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

Concurrent Programming using Threads

Multithreading Pearson Education, Inc. All rights reserved.

Le L c e t c ur u e e 5 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 Exception Handling

Multi-threading in Java. Jeff HUANG

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

User Space Multithreading. Computer Science, University of Warwick

Module - 4 Multi-Threaded Programming

6.Introducing Classes 9. Exceptions

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

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

Threads Questions Important Questions

Animation Part 2: MoveableShape interface & Multithreading

JAVA - MULTITHREADING

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

Multithread Computing

Concurrent Programming

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

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

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

Core Java Interview Questions and Answers.

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

Prashanth Kumar K(Head-Dept of Computers)

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

Object-Oriented Programming Concepts-15CS45

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

Concurrent Computing CSCI 201 Principles of Software Development

04-Java Multithreading

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

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

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

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

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

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Overview of Java Threads (Part 2)

Program #3 - Airport Simulation

Threads Chate Patanothai

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

UNIT:5 EXCEPTION HANDLING & MULTITHREADED

G52CON: Concepts of Concurrency

Chapter 14. Exception Handling and Event Handling ISBN

CS360 Lecture 10 Multithreading

CS 351 Design of Large Programs Threads and Concurrency

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

CS370 Operating Systems

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

What is a thread anyway?

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

MULTI-THREADING

UNIT V CONCURRENT PROGRAMMING

Introduction to Java Threads


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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam.

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

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

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.


Object Oriented Software Design

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Java Threads. Introduction to Java Threads

Object Oriented Software Design

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

Robotics and Autonomous Systems

Java Errors and Exceptions. Because Murphy s Law never fails

CST242 Concurrency Page 1

Performance Throughput Utilization of system resources

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

THREADS AND MULTITASKING ROBOTS

Transcription:

By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology

UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying interfaces, variables in interfaces, extending interfaces. Multithreading :Basic idea of multithreaded programming; The lifecycle of a thread; Creating thread with the thread class and runnable interface; Thread synchronization; Thread scheduling; Producer-consumer relationship; Daemon thread, Selfish threads; Basic idea of exception handling; The try, catch and throw; throws Constructor and finalizers in exception handling; 2

Multithreading :Basic idea of multithreaded programming; Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. 3

The lifecycle of a thread 4

1. New state? After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state? A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 3. Running state? A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 4. Dead state? A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. 5

Different states implementing Multiple-Threads are: Sleeping? On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread. static void sleep(long millisecond) throws InterruptedException 6

Waiting for Notification? A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread. final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException Blocked on I/O? The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources. Blocked for joint completion? The thread can come on this state because of waiting the completion of another thread. Blocked for lock acquisition? The thread can come on this state because of waiting to acquire the lock of an object. 7

Creating thread with the thread class and runnable interface There are two ways of implementing threading in Java 1. By extending java.lang.thread class, or 2. By implementing java.lang.runnable interface. 1. Extending the Thread class: 1. In this method one normal class extends the inbuilt class thread and override its run() method with the code required by that particular thread. 2. Here we are going to extend class java.lang.thread. so we can access all the methods of thread class. 3. Create one class which extends the thread class. 4. Override the run method and put lines of code inside thread method that will be perform by thread. 5. Create an object of class which we created with extending the thread class and call the start() method to execute the thread. 8

Class MyThread extends Thread.... So now we have one thread named MyThread. Implementing the run() method Public void run() // Thread code here Starting new Thread MyThread ath = new MyThread(); // it instantiates a new object of class MyThread ath.start(); // invokes run() method 9

class A extends Thread public void run() System.out.println("Thread A"); for(int i=1;i<=50;i++) System.out.println("From thread A i = " + i); System.out.println("Exit from A"); class B extends Thread public void run() System.out.println("Thread B"); for(int i=1;i<=50;i++) System.out.println("From thread B i = " + i); System.out.println("Exit from B"); public class Thread_Class public static void main(string[] args) new A().start(); //creating A class thread object and calling run method new B().start(); //creating B class thread object and calling run method System.out.println("End of main thread"); 10

2. Implementing the Runnable interface: 1. In this method we have one interface named runnable and we implements this interface for implement a thread. 2. Create one class which implements runnable interface. 3. Override the run() method and put some line of code for that particular thread. 4. Now create an object of inbuilt thread class and create an object of class that implements runnable interface. 5. Give the reference of object to thread object by passing an argument (argument must be the object of class which implements the runnable interface) while creating a thread object. 6. Call the start() method to run the thread. 11

public class Thread_Interface public static void main(string[] args) X x1 = new X(); //class object Thread xthread = new Thread(x1); //creating thread object and giving reference of class object to thread object xthread.start(); System.out.println("End of main Thread"); Output : class X implements Runnable public void run() System.out.println("Inside X thread"); for(int i=1;i<=10;i++) System.out.println("From xthread i = " +i); System.out.println("Exit from X"); End of main Thread Inside X thread From xthread i = 1 From xthread i = 2 From xthread i = 3 From xthread i = 4 From xthread i = 5 From xthread i = 6 From xthread i = 7 From xthread i = 8 From xthread i = 9 From xthread i = 10 Exit from X 12

Java thread scheduling & thread Priority: Features : 1.The JVM schedules using a preemptive, priority based scheduling algorithm. 2.All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM. 3.In case two threads have the same priority a FIFO ordering is followed. 4.In Java program, you create threads but they are not executed by Java alone. Java takes the help of the underlying OS to execute them. 5. To allocate microprocessor time and to supervise all the threads' execution, the OS comes with Thread Scheduler. 6. The entire responsibility of maintaining the sequence of execution of threads, where which thread should be given first preference than the other, lies with the thread scheduler. 7. The scheduling depends on the algorithm of the scheduler. Many types of algorithms exist like preemptive and time slicing with round robin etc. 13

Java thread scheduling & thread Priority: 1. Each java thread has its own priority which decides the order of thread to be schedule. 2. The threads of equal priority will be given same treatment by java scheduler. And they will follow the FCFS (First Come First Serve) algorithm. 3. User can also set the priority of thread by using the setpriority() method as follow: ThreadName.setPriority(int Number); Here the number is integer value between 1 to 10, Here 1 is minimum priority 10 is maximum priority. The Thread class defines few priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 In any Thread the default priority is NORM_PRIORITY Whenever more than one threads are ready to run java system select the highest priority thread and execute it If another thread of higher priority comes the running thread will be preempted by the incoming thread and current thread will move to runnable state. 14

class A extends Thread public void run() System.out.println("ThreadA strated"); for(int i = 1; i<=5; i++) System.out.println("\t From ThreadA i = " +i); System.out.println("Exit from A"); public class Thread_Priority public static void main(string[] args) A threada = new A(); B threadb = new B(); threada.setpriority(thread.min_priority); threadb.setpriority(threada.getpriority()+3); System.out.println("Start Thread A"); threada.start(); class B extends Thread public void run() System.out.println("ThreadB strated"); for(int j = 1; j<=5; j++) System.out.println("\t From ThreadB j = " +j); System.out.println("Exit from B"); System.out.println("Start Thread B"); threadb.start(); System.out.println("End of main Thread"); Output: Start Thread A Start Thread B End of main Thread ThreadB strated From ThreadB j = 1 From ThreadB j = 2 From ThreadB j = 3 From ThreadB j = 4 From ThreadB j = 5 Exit from B ThreadA strated From ThreadA i = 1 From ThreadA i = 2 From ThreadA i = 3 From ThreadA i = 4 From ThreadA i = 5 Exit from A 15

Thread synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this synchronization is achieved is called thread synchronization. The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock. This is the general form of the synchronized statement: synchronized(object) // statements to be synchronized 16

Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object's monitor. 17

Java - Exceptions Handling 18

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. 19

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. 20

try //Protected code catch(exceptionname e1) //Catch block import java.io.*; public class ExcepTest public static void main(string args[]) try int a[] = new int[2]; System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); System.out.println("Out of the block"); 21

Multiple catch Blocks: try //Protected code catch(exceptiontype1 e1) //Catch block catch(exceptiontype2 e2) //Catch block catch(exceptiontype3 e3) //Catch block 22

The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. 23

The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. try //Protected code catch(exceptiontype1 e1) //Catch block catch(exceptiontype2 e2) //Catch block catch(exceptiontype3 e3) //Catch block finally //The finally block always executes. 24

public class ExcepTest public static void main(string args[]) int a[] = new int[2]; try System.out.println("Access element three :" + a[3]); catch(arrayindexoutofboundsexception e) System.out.println("Exception thrown :" + e); finally a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); Exception thrown :java.lang.arrayindexoutofboundsexception: 3 First element value: 6 The finally statement is executed 25

class MyException extends Exception public MyException(String msg) super(msg); public class MyTest static int divide(int first,int second) throws MyException if(second==0) throw new MyException("can't be divided by zero"); return first/second; public static void main(string[] args) try System.out.println(divide(4,0)); catch (MyException exc) exc.printstacktrace(); 26

27