Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Internet Software Development More stuff on Threads Paul Krause.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
 Traditionally, a process in an operating system consists of an execution environment and a single thread of execution (single activity).  However,
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
10/10/20151 MULTITHREADED PROGRAMMING. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
10/17/2015Vimal1 Threads By 10/17/2015Vimal2 Why use threads?? It is a powerful programming tool Computer users take it for granted.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
111 © 2002, Cisco Systems, Inc. All rights reserved.
Computer Engineering Rabie A. Ramadan Lecture 8. Agenda 2 Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
1 Multithreaded Programming using Java Threads Prof. Rajkumar Buyya Cloud Computing and Distributed Systems (CLOUDS) Laboratory Dept. of Computer Science.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Threading and Concurrency COM379T John Murray –
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
THREAD MODEL.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
6/11/2016 DEPT OF CSE 1 JAVA. 6/11/2016 DEPT OF CSE 2 MULTITHREADED PROGRAMMING.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
Multithreading / Concurrency
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
Multithreaded Programming in Java
Multithreading in Java
Multithreading programming Pavan d.m.
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

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 systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next.

 The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.

Thread states Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

Creating Threads Threads are implemented in the form of objects that contain a method called run() run() method contains the entire body of the thread. It is the only method in which the thread’s behavior can be implemented.

Contd…. Public void run() { ……… ……(stmt for implementing thread) } A new thread can be createdin two ways:  By creating a thread class  By converting a class to a thread

By creating a thread class:- define a class that extends Thread class and override its run() method with the code required by the thread. By converting a class to a thread:- Define a class that implements Runnable inteface. The runnable inteface has only one method, run() that is to be defined in the method with the code to be executed by the thread.

Extending the thread class 1.Declare the class as extending the thread class. 2.Implement the run( ) method that is responsible for executing the sequence of code that the thread will execute. 3.Create the thread object and call the start( ) method to initiate the thread execution.

Creating a thread class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t form threadA: i= " +i); } System.out.println("Exit form A"); }

Contd… class threadtest1 { public static void main( String s[ ]) { new A().start(); }

Creating multiple thread using Thread class class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t form threadA: i= " +i); } System.out.println("Exit form A"); }

Contd…… class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\t form threadB: j= " +j); } System.out.println("Exit form B"); }

Contd…. class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t form threadC: k= " +k); } System.out.println("Exit form C"); }

Contd…. class threadtest { public static void main( String s[ ]) { new A().start(); new B().start(); new C().start(); }

Stopping and Blocking a thread 1.Stopping a thread:- whenever we want to stop a thread from running, we can do by calling the stop() method. for example:- obeject_name.stop(); Above statement causes the thread to the dead state automatically when its reaches the end of its method. The stop() method may be used when the premature death of a thread is desired.

Blocking a threads A thread can also be temporarily suspended or blocked from entering into the runnable and subsequently running state by using either of the following thread methods:  sleep( ) // blocked for a specified time.  suspend( ) // blocked until further orders.  wait( ) // blocked until certain condition occurs.

Use of yield(), stop(), and sleep() methods class A extends Thread { public void run() { for(int i=1;i<=5;i++) { if(i==1) yeild(); System.out.println("\t form threadA: i= " +i); } System.out.println("Exit form A"); }

Contd…. class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\t form threadB: j= " +j); if(j==3) stop(); } System.out.println("Exit form B"); }

Contd…… class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t form threadC: k= " +k); if(k==1) try { sleep(1000); } catch( Exception e) { } } System.out.println("Exit form C"); }

Contd… class threadtest { public static void main( String s[ ]) { A threadA= new A(); B threadA= new B(); C threadA= new C(); threadA.start(); threadB.start(); threadC.start(); }

Yield():- Currently executed thread object to be temporarily pause and allow other threads to execute.

using isAlive() and join() Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here: final boolean isAlive( ) The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.

While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ) final void join( ) throws InterruptedException This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

How to use the isAlive() and Join() class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread }

// This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); }

class DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: "+ ob1.t.isAlive()); System.out.println("Thread Two is alive: "+ ob2.t.isAlive()); System.out.println("Thread Three is alive: "+ob3.t.isAlive()); // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join();

ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: “ + ob1.t.isAlive()); System.out.println("Thread Two is alive: “ + ob2.t.isAlive()); System.out.println("Thread Three is alive: “ + ob3.t.isAlive()); System.out.println("Main thread exiting."); }

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 is achieved is called synchronization. Key to synchronization is the concept of the monitor (also called a semaphore). 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 attempting to enter the locked monitor will be suspended until the first thread exits the monitor