CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.

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

1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Multithreading The objectives of this chapter are:
Concurrency…leading up to writing a web crawler. Web crawlers.
Slides prepared by Rose Williams, Binghamton University ICS201 Lectures 18 : Threads King Fahd University of Petroleum & Minerals College of Computer Science.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Threads CS Introduction to Operating Systems.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
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.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Java Threads Representation and Management of Data on the Internet.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
 2004 Deitel & Associates, Inc. All rights reserved. 1 Chapter 4 – Thread Concepts Outline 4.1 Introduction 4.2Definition of Thread 4.3Motivation for.
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.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Threads.
Concurrent Programming and Threads Threads Blocking a User Interface.
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.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading in JAVA
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Java Thread Programming
Chapter 4 – Thread Concepts
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Chapter 4 – Thread Concepts
Chapter 19 Java Never Ends
Threads Chate Patanothai.
Multithreading Chapter 23.
Multithreading.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreaded Programming
Java Thread.
Multithreading in java.
Threads and Multithreading
Representation and Management of Data on the Internet
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009

Threads So far, everything we have done has involved a single sequence of events (although a GUI and the garbage collector may be doing other things) when we invoked a method at line X in our code, Java goes off and executes that method, and only once it is finished does it return control to X+1, and continues from there. but Java also allows us to set off separate threads of execution, called threads, which run concurrently …we call this multi-threading Threads are a way for a program to fork (or split) itself into two or more simultaneously (or pseudo-simultaneously) running tasks

Features of Multi-threading Reactive programming – do more than one thing as a reactive response to some input – e.g. GUIs Controllability – ability to suspend, resume, and stop threads Asynchronous Messages – avoid waiting for unrelated actions to complete –Perform blocking I/O without blocking the entire program Parallelism – on machines with multiple processors can improve on performance

Support in Java Multithreading support in Java from beginning – based on Simula and Mesa –Java 5 incorporated many additions and clarifications to the Java concurrency model “Built-in support for threads provides Java programmers with a powerful tool to improve interactive performance of graphical applications.” Java Language Environment White Paper, Gosling and McGilton The term thread-safe means that a given library function is implemented in such a manner that it can be executed by multiple concurrent threads of execution

Thread states A new thread begins in the new state It transitions to the runnable state when the program starts the thread A thread transitions to the waiting state while another thread performs a task A runnable thread can transition to a timed waiting state for a specified interval of time

Concurrent Execution Each thread in the runnable state runs for a short period of time and then the computer system switches to another thread (it is dispatched) The operating system’s thread scheduler determines which thread runs next Normally each thread is given a small amount of time called a time- slice or a quantum This gives the illusion that the threads are running in parallel Actually threads may run in parallel on multi-processor or multi-core systems

Threads Two ways to run a thread: (i) Subclass Thread; (ii) Implement Runnable interface (preferable) Java supplies a class Thread, which allows us to start a separate thread of execution A Thread object has a run() method, which tells the system what to do during this thread To start a thread, use the start() method, which then invokes the run() method By default, run() does nothing – you must override it to do what you want.

Ping pong example public class Pinger extends Thread { public void run() { for (int i = 0; i<100; i++) System.out.print("ping..."); } public class Ponger extends Thread { public void run() { for (int i = 0; i<100; i++) System.out.print("... pong"); }

Playing Ping Pong public class PingPong { public static void main(String[] args); Pinger pinger = new Pinger(); Ponger ponger = new Ponger(); pinger.start(); ponger.start(); } start() starts its thread, then immediately hands back control, so that the second thread can begin. Both threads run concurrently. start() starts its thread, then immediately hands back control, so that the second thread can begin. Both threads run concurrently.

Threads using interfaces Instead of directly subclassing Thread, we can implement the Runnable interface, by specifying the run() method 1.Create class implementing Runnable 2.Specify run() method 3.Create object of class 4.Construct a Thread object from Runnable object 5.Call the start() method of Thread Advantages of this approach Can use thread pools (see later) Inheritance is still available to your class

Runnable Runnable interface is very simple. The class must define a method of no arguments called run. public interface Runnable { public abstract void run() { } class Mine implements Runnable { public void run() { //code here }

Ping Pong using Runnable public class Pinger implements Runnable { public void run() { for (int i = 0; i<100; i++) System.out.println("ping..."); } public class PingPong { public static void main(String[] args) { Thread t1 = new Thread(new Pinger()); Thread t2 = new Thread(new Ponger()); t1.start(); t2.start(); }

Remarks each call to start() begins a new thread a call to run() does not begin a new thread – it just begins the computation in the existing thread the two threads in PingPong are almost identical, so they operate more or less in step with each other... –... but not necessarily – actual behaviour depends on the scheduling policy of the underlying platform to "guarantee" good behaviour, you must control the threads, by putting one to sleep, etc.

Put thread to Sleep To wait use the static method sleep of Thread class. Thread.sleep(2000) // sleep for 2 seconds A sleeping thread can be interrupted. When this occurs an InterruptedException occurs. You need to catch this. Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received. catch (InterruptedException e) { //We've been interrupted: stop what we were doing. return; }

Sleep Example public class Greet implements Runnable { public void run() { try { for (int i=1; i < 10; i++) { System.out.println(“Tick”); Thread.sleep(1000); } catch (InterrupedException e) { System.out.println(“Thread interrupted”); }

join() The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join(); causes the current thread to pause execution until t 's thread terminates. Overloads of join allow the programmer to specify a waiting period. Like sleep, join responds to an interrupt with an InterruptedException.