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

Size: px
Start display at page:

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

Transcription

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

2 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

3 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

4 The lifecycle of a thread 4

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 Java - Exceptions Handling 18

19 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

20 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

21 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

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

23 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

24 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

25 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

26 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 27

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

More information

CIS233J Java Programming II. Threads

CIS233J Java Programming II. Threads CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential

More information

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

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

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 Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

Multithreading using Java. Dr. Ferdin Joe John Joseph

Multithreading using Java. Dr. Ferdin Joe John Joseph Multithreading using Java Dr. Ferdin Joe John Joseph 1 Agenda Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing Shared Resources Synchronisation Assignment

More information

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

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

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

JAVA. Lab 12 & 13: Multithreading

JAVA. Lab 12 & 13: Multithreading JAVA Prof. Navrati Saxena TA: Rochak Sachan Lab 12 & 13: Multithreading Outline: 2 What is multithreaded programming? Thread model Synchronization Thread Class and Runnable Interface The Main Thread Creating

More information

Object Oriented Programming. Week 10 Part 1 Threads

Object Oriented Programming. Week 10 Part 1 Threads Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that

More information

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

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 1 Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Hwansoo Han T.A. Jeonghwan Park 41 T.A. Sung-in Hong 42 2 Exception An exception

More information

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

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

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

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1

More information

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

Object Oriented Programming (II-Year CSE II-Sem-R09) (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

More information

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

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

More information

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

More information

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

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

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

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

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading Pearson Education, Inc. All rights reserved. 1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

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

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

User Space Multithreading. Computer Science, University of Warwick

User Space Multithreading. Computer Science, University of Warwick User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

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

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program

More information

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

Multithread Computing

Multithread Computing Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

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

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India RESEARCH ARTICLE Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP-201303 - India OPEN ACCESS ABSTRACT This paper contains information

More information

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

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

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

Java Threads. Written by John Bell for CS 342, Spring 2018 Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.

More information

Core Java Interview Questions and Answers.

Core Java Interview Questions and Answers. Core Java Interview Questions and Answers. Q: What is the difference between an Interface and an Abstract class? A: An abstract class can have instance methods that implement a default behavior. An Interface

More information

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

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

Prashanth Kumar K(Head-Dept of Computers)

Prashanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-IV 1 1. What is Thread? Thread is a task or flow of execution that can be made to run using time-sharing principle.

More information

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

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Object-Oriented Programming Concepts-15CS45

Object-Oriented Programming Concepts-15CS45 Chethan Raj C Assistant Professor Dept. of CSE Module 04 Contents 1. Multi Threaded Programming 2. Multi Threaded Programming 3. What are threads 4. How to make the classes threadable 5. Extending threads

More information

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

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2) Network Programming COSC 1176/1179 Lecture 6 Concurrent Programming (2) Threads Recall from last week Every line of Java code is part of a thread There can be one or more threads running in parallel Each

More information

Concurrent Computing CSCI 201 Principles of Software Development

Concurrent Computing CSCI 201 Principles of Software Development Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking

More information

04-Java Multithreading

04-Java Multithreading 04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org

More information

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

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 Contents G53SRP: Java Threads Chris Greenhalgh School of Computer Science 1 Definition Motivations Threads Java threads Example embedded process Java Thread API & issues Exercises Book: Wellings 1.1 &

More information

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

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

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

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 Session objectives Introduction Creating thread Thread class

More information

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

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

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

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004 Thread Programming Comp-303 : Programming Techniques Lecture 11 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 11 Comp 303 : Programming Techniques Page 1 Announcements

More information

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

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

Overview of Java Threads (Part 2)

Overview of Java Threads (Part 2) Overview of Java Threads (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Program #3 - Airport Simulation

Program #3 - Airport Simulation CSCI212 Program #3 - Airport Simulation Write a simulation for a small airport that has one runway. There will be a queue of planes waiting to land and a queue of planes waiting to take off. Only one plane

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

UNIT:5 EXCEPTION HANDLING & MULTITHREADED

UNIT:5 EXCEPTION HANDLING & MULTITHREADED UNIT:5 1 EXCEPTION HANDLING & MULTITHREADED TOPICS TO BE COVERED 5.1 Types of errors Exceptions try..catch statement Multiple catch blocks Throw and Throws keywords finally clause Uses of exceptions User

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Java implementations of concurrency process and threads

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

CS360 Lecture 10 Multithreading

CS360 Lecture 10 Multithreading Tuesday, March 9, 2004 Reading Exception Handling: Chapter 15 Multithreading: Chapter 16 CS360 Lecture 10 Multithreading Declaring New Exception Types Most programmers use existing exception classes from

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

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

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall() 9 Threads Certification Objectives l l l Start New Threads Recognize Thread States and Transitions Use Object Locking to Avoid Concurrent Access l Write Code That Uses wait(), notify(), or notifyall()

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

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

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 2018 Lecture 8 Threads and Scheduling Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ How many threads

More information

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

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

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.

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. Deadlock A set of processes is deadlocked if each process in the set is waiting for an event that can be caused by another process in the set. The events that we are mainly concerned with are resource

More information

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

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1 Java Threads Instructor: t Mainak Chaudhuri mainakc@cse.iitk.ac.iniitk ac 1 Java threads Two ways to create a thread Extend the Thread class and override the public run method Implement a runnable interface

More information

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

MULTI-THREADING

MULTI-THREADING MULTI-THREADING KEY OBJECTIVES After completing this chapter readers will be able to understand what multi-threaded programs are learn how to write multi-threaded programs learn how to interrupt, suspend

More information

UNIT V CONCURRENT PROGRAMMING

UNIT V CONCURRENT PROGRAMMING UNIT V CONCURRENT PROGRAMMING Multi-Threading: Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Unit III Exception Handling and I/O Exceptions-exception hierarchy-throwing and catching exceptions-built-in exceptions, creating own exceptions, Stack Trace Elements. Input /Output Basics-Streams-Byte

More information

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

Definition: A thread is a single sequential flow of control within a program. What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

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

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam. Exam Number/Code : 1Z0-851 Exam Name: Name: Java Standard Edition 6 Programmer Certified Professional Exam Version : Demo http://it-shiken.jp/ QUESTION 1 public class Threads2 implements Runnable { public

More information

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright MultiThreading Object Orientated Programming in Java Benjamin Kenwright Outline Review Essential Java Multithreading Examples Today s Practical Review/Discussion Question Does the following code compile?

More information

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

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

More information

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

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment. Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment Overview What constitutes a thread? Instruction pointer Stack space

More information

http://www.ugrad.cs.ubc.ca/~cs219/coursenotes/threads/intro.html http://download.oracle.com/docs/cd/e17409_01/javase/tutorial/essential/concurrency/index.html start() run() class SumThread extends

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 3, 2011 G. Lipari (Scuola Superiore Sant

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant

More information

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

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Shrideep Pallickara Computer Science Colorado State University L6.1 Frequently asked questions from the previous class survey L6.2 SLIDES CREATED BY:

More information

Robotics and Autonomous Systems

Robotics and Autonomous Systems 1 / 38 Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 2 / 38 Today Some more programming techniques that

More information

Java Errors and Exceptions. Because Murphy s Law never fails

Java Errors and Exceptions. Because Murphy s Law never fails Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

THREADS AND MULTITASKING ROBOTS

THREADS AND MULTITASKING ROBOTS ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 comp329-2013-parsons-lect10 2/37 Today Some more programming techniques that will be helpful

More information