JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

Unit - IV Multi-Threading

04-Java Multithreading

Module - 4 Multi-Threaded Programming

JAVA. Lab 12 & 13: Multithreading

Object Oriented Programming. Week 10 Part 1 Threads

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

Amity School of Engineering

Multithreaded Programming

7. MULTITHREDED PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Unit III Rupali Sherekar 2017

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

Software Practice 1 - Multithreading

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

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

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

Unit 5 - Exception Handling & Multithreaded

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

CIS233J Java Programming II. Threads

Synchronization synchronization.

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

UNIT V CONCURRENT PROGRAMMING

Concurrent Programming using Threads

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

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

Multi-threading in Java. Jeff HUANG

CS 556 Distributed Systems

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

Object-Oriented Programming Concepts-15CS45

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

Multithread Computing

Animation Part 2: MoveableShape interface & Multithreading

Threads Chate Patanothai

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

JAVA - MULTITHREADING

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

Multithreading using Java. Dr. Ferdin Joe John Joseph

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

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 Threads. Written by John Bell for CS 342, Spring 2018

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

MULTI-THREADING

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

Concurrent Programming

Synchronized Methods of Old Versions of Java

Multithreaded Programming


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

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

Performance Throughput Utilization of system resources

Multithreaded Programming

Java Threads. Introduction to Java Threads

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

User Space Multithreading. Computer Science, University of Warwick

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming

Chapter 32 Multithreading and Parallel Programming

Multithreaded Programming

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

Java Threads. COMP 585 Noteset #2 1

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

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

Threads in Java (Deitel & Deitel)

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

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Programming Java. Multithreaded Programming

Multithreading Pearson Education, Inc. All rights reserved.

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

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

we dont take any liability for the notes correctness.

Multithreading in Java Part 2 Thread - States JAVA9S.com

Introduction to Java Threads

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

THREADS AND CONCURRENCY

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

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

Threads and Parallelism in Java

G52CON: Concepts of Concurrency

Advanced Concepts of Programming

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

CMSC 330: Organization of Programming Languages

Chapter 19 Multithreading

Prashanth Kumar K(Head-Dept of Computers)

EDAF65 Processes and Threads

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

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

EDA095 Processes and Threads

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.

What is a thread anyway?

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Basics of. Multithreading in Java

Advanced Programming Concurrency

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Programming Language Concepts: Lecture 11

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

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

CERTIFICATION OBJECTIVES

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

Transcription:

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; Implementing runnable; Synchronization; Changing state of the thread; Bounded buffer problems, read-write problem, producer consumer problems.

Introduction Sub unit of a process is handled by a thread. Examples:- Auto save operation as you type in text editor. Computer game which runs music, score, graphics. Animation program.

Threads Thread is similar to a sequential program It has beginning, steps to execute, an end Threads which runs within a program(process) Every thread has at least one thread-primary thread Micro processor allocates memory to the processes that we execute Each process occupies its own address space All the threads in a process share the same address space. Resources( Memory, Devices, Data of program, Environment of a program) are available to all the threads of that program. A thread is also known as a lightweight process or execution context. Because there are fewer overloads on the processor when it switches from one thread to another. Process are heavy weight.

Relationship between Threads and processes

Single Threaded and Multithreaded application

Threads in Java 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. Thus, multithreading is a specialized form of multitasking.

Multi Taksing Process based Thread based

Process based multi tasking Process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example: process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

Thread based multitaskng In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads.

Differences.. Multitasking threads require less overhead than multitasking processes. Processes are heavyweight tasks that require their own separate address spaces. Inter process communication is expensive and limited. Context switching from one process to another is also costly. Threads, on the other hand, are lightweight. They share the same address space and cooperatively share the same heavyweight process. Inter thread communication is inexpensive, and context switching from one thread to the next is low cost.

The Java Thread Model The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles.

Single Threaded Application Every program that we can create has at least one thread. We can access this thread using the currentthread() method of the Thread class This method is a static method. Thread thisthread=thread.currentthread():

Example for single thread public class CurrentThread { public static void main(string args[]) { Thread thisthread =Thread.currentThread(); System.out.println("Current Thread"+ thisthread); try { for(int n=0;n<=10;n++) { System.out.println(n); Thread.sleep(1000); catch (InterruptedException e) { System.out.println("Main Thread exception");

Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread to another. Thread's priority is used to decide when to switch from one running thread to the next. This is called a context switch

Effect of priority A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted

Creating a Thread Extending the Thread class Using Runnable class

Thread class methods Method getname getpriority isalive join run sleep start Description Obtain a thread's name. Obtain a thread's priority Determine if a thread is still running. Wait for a thread to terminate. Entry point for the thread. Suspend a thread for a period of time. Start a thread by calling its run method.

Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of the program The main thread is important for two reasons: It is the thread from which other "child" threads will be spawned. It must be the last thread to finish execution. When the main thread stops, program terminates. Although the main thread is created automatically when your program is started, it can be controlled through a Thread object.

First program revisted.. public class CurrentThread { public static void main(string args[]) { Thread thisthread =Thread.currentThread(); System.out.println("Current thread: " + thisthread ); thisthread.setname("my Thread"); System.out.println("Current Thread"+ thisthread); Try { for(int n=0;n<=5;n++){ System.out.println("Hello"); Thread.sleep(1000); catch (InterruptedException e) {System.out.println("Main Thread exception");

About the program a reference to the current thread (the main thread, in this case) is obtained by calling currentthread( ) This reference is stored in the local variable thisthread The program then calls setname( ) to change the internal name of the thread. Next, a loop counts down from five, pausing one second between each line. The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the delay period in milliseconds. The sleep( ) method in Thread might throw an interruptedexception.

Editing and Compilation Create new Project (Optional) Add new Java source file Run as (Similar to compiling java class files)

Result Current thread: Thread[main,5,main] Current ThreadThread[My Thread,5,main] Hello Hello Hello Hello Hello Hello

About sleep method The sleep( ) method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here: static void sleep(long milliseconds) throws InterruptedException

Creating thread Java defines two ways in which this can be accomplished: implement the Runnable interface. extend the Thread class, itself.

Implementing Runnable You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) Inside run( ), you will define the code that constitutes the new thread. Then instantiate an object of type Thread from within that class. Thread defines several constructors: Thread(Runnable threadob, String threadname) threadob is an instance of a class that implements the Runnable interface. After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. start( ) executes a call to run( ).

Child thread: to generate 10 numbers class ChildThread implements Runnable { Thread t; ChildThread() { t = new Thread(this, New Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread public void run(){// This is the entry point for the second thread. try { for(int i = 5; i > 0; i--){ System.out.println("Child Thread: " + i); Thread.sleep(500); catch (InterruptedException e) {System.out.println("Child interrupted."); System.out.println("Exiting child thread.");

Main thread public class RunnableThreadDemo { public static void main(string[] args) { new ChildThread(); // create a new thread System.out.println("Main thread exiting.");

Extending Thread The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

Example: Extend // Create a second thread by extending Thread class NewThread extends Thread { Thread t; NewThread() { t = new Thread(this, Child Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread public void run()//entry point { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); catch (InterruptedException e) { System.out.println("Exiting child thread.");

Main Thread public class ExtendThreadDemo { public static void main(string args[]) { new NewThread(); // create a new thread System.out.println("Main thread exiting.");

Thread creation using Extend and Runnable two in one example

class ChildThreadRunnable implements Runnable { Thread t1; ChildThreadRunnable() { t1 = new Thread(this, Thread 1"); t1.start(); // Start the thread public void run()//entry point { try { System.out.println("Hello from Runnable Child Thread"); Thread.sleep(5000); catch (InterruptedException e) { System.out.println("Exiting child thread 1!");

class ChildThreadExtend extends Thread { Thread t2; ChildThreadExtend() { t2 = new Thread(this, "Even Thread"); t2.start(); // Start the thread public void run()//entry point { try { System.out.println("Hello from Extended Child Thread"); Thread.sleep(1000); catch (InterruptedException e) { System.out.println("Exiting child thread 2!");

Which approach is better Runnable method Because thread may extend from some other class in such case its better practice to implement runnable method Ex: Userdefined Applet class extend from Applet class to make it as thread use Runnable as multiple extend is not supported by Java Wrong : MyApplet extend Applet extend Thread Right: MyApplet extend Applet implements Runnable

Multiple threads: to handle even and odd number generation Problem statement Design multiple threads using java to demonstrate even and odd number generation each handled by different thread. Two threads with different purposes

Child thread: Even class EvenThread1 implements Runnable { Thread t; EvenThread1() { t = new Thread(this, Even Thread"); t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =0; i <=10 ; i++) { if(i%2==0) System.out.println("Next Even Number:" + i); Thread.sleep(500); catch (InterruptedException e) {System.out.println("Child interrupted."); System.out.println("Exiting Even child thread.");

Child thread: Odd class OddThread1 implements Runnable { Thread t; OddThread1() { t = new Thread(this, "Odd Thread"); t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =0; i <=10 ; i++) { if(i%2!=0) System.out.println("Next Odd Number:" + i); Thread.sleep(500); catch (InterruptedException e) {System.out.println("Child interrupted."); System.out.println("Exiting Odd child thread.");

Main Thread public class MultiThread { public static void main(string args[]) { new EvenThread1(); // create a new thread new OddThread1(); // create a new thread System.out.println("Main thread exiting.");

The Runnable interface consists of a single method, run(), which is executed when the thread is activated. public class thread implements Runnable {...........;

Multiple threads: to handle even and odd number generation Problem statement Design multiple threads using java to demonstrate even and odd number generation each handled by different thread. Two threads with same purposes

class Thread1 implements Runnable { Thread t; String name; int delay; Thread1(String name,int delay) { t = new Thread(this, name); this.name=name; this.delay=delay; t.start(); // Start the thread public class MultiThread2 { public static void main(string args[]) { new Thread1("First",1000); new Thread1("Second",2000); new Thread1("Third",3000); System.out.println("Main thread exiting."); // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =1; i <=5 ; i++) {System.out.println("Next Number:" + i+ " generated by :"+name); Thread.sleep(delay); catch (InterruptedException e) { System.out.println("Exiting Even child thread.");

One instance of output Next Number:1 generated by :Second Next Number:1 generated by :First Main thread exiting. Next Number:1 generated by :Third Next Number:2 generated by :First Next Number:3 generated by :First Next Number:2 generated by :Second Next Number:4 generated by :First Next Number:2 generated by :Third Next Number:3 generated by :Second Next Number:5 generated by :First Exiting child thread: First Next Number:4 generated by :Second Next Number:3 generated by :Third Next Number:5 generated by :Second Next Number:4 generated by :Third Exiting child thread: Second Next Number:5 generated by :Third Exiting child thread :Third * This need not be same always

Life Cycle of Thread 1. New 2. Runnable 3. Dead 4. Blocked

Life cycle of a Thread

Blocked thread Thread goes to sleep by calling the sleep The thread calls an operation that is blocking on I/O The tries to acquire a lock that is currently held by another thread. The thread waits for a condition Any other can call suspend method of the thread

Blocked state to active If a thread has been put to sleep, the specified number of msec must expire. If a thread is waiting for the completion of an I/O, then the operation must have finished. If a thread is waiting for a lock that was owned by another thread, then the other thread must relinquish ownership of the lock. If a thread waits for a condition, then another thread must signal that the condition may have changed.

Dead thread It dies a natural death because the run() method exits normally. It dies abruptly because an uncaught exception terminates the run method. We cannot restart a dead thread. We cannot call the methods of a dead thread.

Priority of a Thread JRE executes threads based on their priority A CPU can execute only one thread at a time The threads that are ready for execution queue up for processor time. Each thread is given a slice of time after which it goes back into the thread queue. The threads are scheduled using fixed priority scheduling principle. Each thread has a priority that affects its position in the thread queue of the processor A thread with higher-priority runs before threads with low-priority Priority can be set by setpriority(); Syntax: public final void setpriority(int newpriority); Three constants are: 1. MIN_PRIORITY 2. MAX_PRIORITY 3. NORM_PRIORITY Default priority is 5

isalive() and join() methods These are used to determine whether a thread has finished or not First isalive() method is called, which returns true (if thread is still running) or false (otherwise). join() method is used to ensure that a thread has stopped.

Demo:Small modification to main only

class Thread1 implements Runnable { Thread t; String name; int delay; Thread1(String name,int delay) { t = new Thread(this, name); this.name=name; this.delay=delay; t.start(); // Start the thread // This is the entry point for the second thread. public void run()//assign work here { try { for(int i =1; i <=5 ; i++) {System.out.println("Next Number:" + i+ " generated by :"+name); Thread.sleep(delay); catch (InterruptedException e) { System.out.println("Exiting Even child thread.");

public class IsAliveDemo { public static void main(string args[]) { Threads t1=new Threads("First",1000); // create a new thread Threads t2=new Threads("Second",2000); // create a new thread Threads t3=new Threads("Third",3000); // create a new thread System.out.println("Thread One is alive: + t1.t.isalive()); System.out.println("Thread Two is alive: + t2.t.isalive()); System.out.println("Thread Three is alive: + t3.t.isalive()); System.out.println("Main thread exiting."); try { System.out.println("Waiting for threads to finish."); t1.t.join(); t2.t.join(); t3.t.join(); catch (InterruptedException e) {System.out.println("Main thread Interrupted"); System.out.println("Thread One is alive: "+ t1.t.isalive()); System.out.println("Thread Two is alive: "+ t2.t.isalive()); System.out.println("Thread Three is alive: "+ t3.t.isalive());

Output Next Number:1 generated by :First Next Number:4 generated by :Second Next Number:1 generated by :Second Next Number:3 generated by :Third Thread One is alive: true Next Number:5 generated by :Second Thread Two is alive: true Next Number:4 generated by :Third Thread Three is alive: true Exiting child thread:second Main thread exiting. Next Number:5 generated by :Third Waiting for threads to finish. Exiting child thread:third Next Number:1 generated by :Third Thread One is alive: false Next Number:2 generated by :First Thread Two is alive: false Next Number:3 generated by :First Thread Three is alive: false Next Number:2 generated by :Second Next Number:4 generated by :First Next Number:2 generated by :Third Next Number:5 generated by :First Next Number:3 generated by :Second Exiting child thread:first

Need for synchronization When two or more threads need access to a shared resources, they need some way to ensure that the resources will be used by only one thread at a time. The process by which this is achieved is called synchronization.

Background A monitor or semaphore is the key concept behind synchronization. A monitor is an object that is used as a mutually exclusive lock or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads are said to be waiting for the monitor A thread that owns a monitor can re-enter the same monitor. In Java synchronization is achieved by synchronized key word.

Synchronization... By calling sleep( ), the call( ) method allows execution to switch to another thread. This results in the mixed-up output of the three message strings. In this program, nothing exists to stop all three threads from calling the same method, on the same object, at the same time. This is known as a race condition, because the three threads are racing each other to complete the method.

Demo program to print message Problem statement: Design multi thread program in Java to print Message Hello World From Java Each word need to displayed by 4 thread Message to be displayed is single world This could be treated as target block So target block is called be each caller thread Without synchronization output might be: World Hello Java From Java From Java World World Java Hello From

How to fix this problem? To fix the preceding program, you must serialize access to call( ). That is, you must restrict its access to only one thread at a time. To do this, you simply need to precede call( )'s definition with the keyword synchronized, as shown here: class Callme { synchronized void call(string msg) {... This prevents other threads from entering call( ) while another thread is using it.

Inter -thread communication wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same object. notifyall( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.