Unit 8: Threads. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

Similar documents
CIS233J Java Programming II. Threads

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Multithreading in Java Part 2 Thread - States JAVA9S.com

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

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

Animation Part 2: MoveableShape interface & Multithreading

What is a thread anyway?

CS 556 Distributed Systems

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

Multi-threaded programming in Java

Threads Questions Important Questions

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

Concurrent Programming using Threads

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

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

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

CS506 today quiz solved by eagle_eye and naeem latif.mcs. All are sloved 99% but b carefull before submitting ur own quiz tc Remember us in ur prayerz

Chapter 19 Multithreading

Object Oriented Programming. Week 10 Part 1 Threads

Concurrent Programming

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

Lecture 13 Condition Variables

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads

IT101. Graphical User Interface

Concurrent Computing CSCI 201 Principles of Software Development

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

Performance Throughput Utilization of system resources

Figure 6.1 System layers

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

Unit5: Packages and abstraction. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

Multithread Computing

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

Java: Pitfalls and Strategies

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

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

CST242 Concurrency Page 1

Java Threads. COMP 585 Noteset #2 1

CS360 Lecture 12 Multithreading

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

Core Java Contents. Duration: 25 Hours (1 Month)

Multithreaded Programming

Lecture 7: Process & Thread Introduction

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

7. MULTITHREDED PROGRAMMING

G52CON: Concepts of Concurrency

Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub

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

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

Operating System Support

Introduction to Java Threads

Threads Chate Patanothai

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 5, 2009 Objectives

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA MOCK TEST JAVA MOCK TEST III

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

CS342: Software Design. November 21, 2017

연세대학교전기전자공학과프로세서연구실박사과정김재억.

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

Operating System. Chapter 4. Threads. Lynn Choi School of Electrical Engineering

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

UNIT V CONCURRENT PROGRAMMING

Chapter 4: Multithreaded

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

COMP 401 ANIMATION, THREADS, COMMAND OBJECTS. Instructor: Prasun Dewan

MVP1: Introduction to concurrency in JAVA

Stacks and Queues

Chapter 6 Introduction to Defining Classes

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 11, 2007 Objectives

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

آنستیتیوت تکنالوجی معلوماتی و مخابراتی ICTI

Threads Assistant Professor DCS Operating System Concepts

Synchronization in Concurrent Programming. Amit Gupta

Lecture 17: Threads and Scheduling. Thursday, 05 Nov 2009

THREADS AND CONCURRENCY

Multithreaded Programming

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

SELF-STUDY. Glossary

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

Chapter 4: Threads. Chapter 4: Threads. Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Software Practice 1 - Multithreading

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

THREADS & CONCURRENCY

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

PART1: Choose the correct answer and write it on the answer sheet:

A6 AND A START ON THREADS AND CONCURRENCY

INHERITANCE. Spring 2019

CS180 Review. Recitation Week 15

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

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

15CS45 : OBJECT ORIENTED CONCEPTS

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Concurrent Programming Lecture 10

Assigned Date: August 27, 2014 Due Date: September 7, 2015, 11:59 PM

Multithreading using Java. Dr. Ferdin Joe John Joseph

Transcription:

Unit 8: Threads Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15 1

1. Introduction 2. Creating Threads 3. Review SAQ 2

1. Introduction Threads are separate activities within a program, each of which has a beginning and an end. Example: You might want to monitor the keyboard for a key being pressed by a user and, at the same time, track the movement of the mouse by the user and repaint the screen. Each of these tasks can be thought of as a single thread in program. The Java system has a component known as the scheduler that makes decisions about which thread to run next. Threads are not the actual static code itself but rather they are the dynamic process of executing that code So far, all of the programs that you have written have had only one thread and this has been the thread started by the main method. 3

Concurrent systems 1. Introduction It is an area of computer science that represents the concepts surrounding the use of threads. a concurrent system consists of a collection of separate activities or tasks that are simultaneously at some stage between their starting and finishing point. In a concurrent system, each task is made into a thread and on a multiprocessor computer, each thread can truly run at the same time as all of the other threads (up to the number of processors available, of course). on a single-processor computer, the CPU can carry out only one set of instructions at a time. In this situation the threads share the CPU, and the operating system will allocate small blocks of time to each thread. 4

1. Introduction 2. Creating Threads 3. Review SAQ 5

A thread is treated as an object in Java and the Thread class is found in the java.lang library. The Thread class has a number of methods for creating, destroying and modifying threads. Threaded classes can be defined in two ways: (1) by inheriting from the Thread class This method is used if you wish to inherit from only one class, the Thread class. Note that Java does not allow multiple inheritance (2) or by implementing the Runnable interface. Defining threads by implementing the Runnable interface is used when you want to inherent from a class other than the Thread class. 6

2.1 Inheriting from the Thread class The general approach is (1) Define a class by extending the Thread class and overriding the run method. In the run method, you should write the code that you wish to run when this particular thread has started. (2) Create an instance of the above class (3) Start running the instance using the start method that is defined in Thread. Example The output 7

2.2 Implementing the Runnable interface The general approach is (1) Define a class that implements Runnable and overriding the run method. (2) Create an instance of the above class. (3) Create a thread that runs this instance. (4) Start running the instance using the start method. Example The output 8

2.3 Thread states We need to look at the various states that a thread can be in and how a thread might move from one state to another. A thread is in one of five states at any moment in time: (1) initial state; (2) runnable state; (3) running state; (4) blocked state; (5) finished state. The figure shows the possible transitions between states. 9

Movement from one state to another is governed by: (1) a number of methods from Thread class and the Object class (2) the operating system and other external factors. Note the following in the figure: A thread is put into the initial state by means of it being created using new. the start method moves the thread into the runnablestate. This does not mean that it will run immediately (there may be another thread that is being run by the CPU) At certain times during the execution of a program that contains threads, the Java system will have a look at all the runnable threads and will select one to execute. Only the thread that is actually executing is said to be in the running state. When a particular thread is chosen, its run method is invoked and the thread can begin to execute the code. It is now in the running state. When a running state finishes executing, it moves into the finished state. 10

However, the thread may run out of its allotted CPU time. Alternatively, it may invoke the yield method to give way to other threads of equal or higher priority. Both scenarios will cause the thread to go back into the runnablestate where it can, at some point, be chosen by the Java runtime system to move back into the running state. Once it is back in the running state it can carry on with the execution of its run method at the point where it left off. This is indicated by the resumelabel in the figure. 11

From the running state, a thread may move to the blocked state because of delays in I/O, or because the sleepmethod or wait method is invoked. The sleep method is a static method of Thread and so can be called in any program, even those that do not use the Thread class. When invoked, it puts the thread to sleep for the specified number of milliseconds. In the blocked state, the thread cannot progress until something happens for example, an I/O transfer is completed. 12

The wait, notify and notifyall methods: All three methods are inherited from the Object class rather than the Thread class The wait method causes a thread to wait for notification by another thread, The notify and notifyallprovide such notification. 13

The important concept at this stage is that a Java program may involve a number of threads, some of which are runnableand ready to be executed by a processor and others that are unable to proceed because they are blocked. On a single-processor machine only one thread can actually be running at a time. The Java system has a component known as the schedulerthat makes decisions about which thread to run next. The decision as to when thread execution is switched will depend on the underlying operating system: some operating systems switch when the currently running thread becomes blocked, while others allocate set blocks of time to a thread. 14

15

3-Review SAQ Review SAQ 1 Page 13 (a) What are the two ways to define threads? (b) When a thread is executing, does it continue executing until it gets to the end of its code? (c) How do you tell the system that you want to set a thread running? ANSWERS... (a) Threads can be defined by extending the Thread class or by implementing the Runnableinterface. (b) No, in all likelihood the thread will have access to the CPU for only a short part of its execution before it is stopped and another thread is given an opportunity to run. (c) After creating an instance of a threaded class, you invoke the start method. 16

Review SAQ 2 Page 14 3-Review SAQ (a) When would you typically want to define a thread by implementing Runnablerather than extending Thread? (b) How do you define, create and start a thread using Runnable? ANSWERS... (a) There are many occasions when a threaded class will inherit from another class: for example, JFrame. As Java does not allow multiple inheritance it is useful to be able to implement an interface to create a thread. Remember, Java allows a class to implement any number of interfaces but to extend only one other class. (b) The thread class is defined by implementing the interface Runnableand the single method in the interface run. You then create an instance of this threaded class and pass this instance to the Thread constructor to create a new threaded object. This can then be treated as any other threaded object and can be started by invoking the start method. 17

Review SAQ 5 Page 30 3-Review SAQ (a) What is the difference between a thread in the blockedstate and one in the runnablestate? ANSWERS... (a) A runnablethread is fully ready to run once it is chosen by the scheduler. On the other hand, a thread in the blocked state is definitely not ready to run because it is waiting for something to happen. It may be waiting either for an I/O event to happen or because the wait method has been invoked. 18