Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Advertisements

Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
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
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.
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.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
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.
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)
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()
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
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.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
Threads.
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.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Multithreading in JAVA
Threading and Concurrency COM379T John Murray –
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.
SurfaceView.
Multi-Threading in Java
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 More on Thread API.
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.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
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.
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Multithreading (Based on Chapter 29 (Multithreading) Liang book and Chapter 5 (Threads) Elliotte Rusty book) Dr. Tatiana Balikhina 1.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
EE 422C Multithreading & Parallel Programming
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
برنامه‌نویسی چندنخی Multi-Thread Programming
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Presentation transcript:

Advanced Programming Estifanos T. (MSc in Computer Networking)

CHAPTER THREE Multithreading Concept Estifanos T. (MSc in Computer Networking)

Objectives 3 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) To explain Threads Vs Process To describe the Multiple Threads To discuss Thread Priorities To explore Thread Synchronization

Introduction 4 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking)

Introduction 5 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking)

Introduction 6 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Thread: single sequential flow of control within a program Single-threaded program can handle one task at any time Multitasking allows single processor to run several concurrent threads Most modern operating systems support multitasking

Multithreading 7 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) video interaction networking Video Game Process

Advantages of Multithreading 8 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Reactive Systems – constantly monitoring More responsive to user input – GUI application can interrupt a time- consuming task Server can handle multiple clients simultaneously Can take advantage of parallel processing Different processes do not share memory space A thread can execute concurrently with other threads within a single process All threads managed by the JVM share memory space and can communicate with each other

Threads Concept 9 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Multiple Threads On Multiple CPUs Multiple Threads Sharing A Single CPUs

Threads in Java 10 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Creating threads in Java: Extend java.lang.Thread class OR Implement java.lang.Runnable interface

Threads in Java 11 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Creating threads in Java via Extend java.lang.Thread class run() method must be overridden (similar to main method of sequential program) run() is called when execution of the thread begins A thread terminates when run() returns start() method invokes run() Calling run() does not create a new thread

Threads in Java 12 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Creating threads in Java via Implement java.lang.Runnable interface If already inheriting another class (i.e., JApplet) Single method: public void run() Thread class implements Runnable

Threads States 13 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking)

Threads Termination 14 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) A thread becomes Not Runnable when one of these events occurs: Its sleep method is invoked The thread calls the wait method to wait for a specific condition to be satisfied The thread is blocking on I/O

Creating Threads Demo 1 15 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) class Output extends Thread { private String toSay; public Output (String st) { toSay = st; } public void run() { try { for ( int i=1; i<=2; i++) { // you can change the iteration as you want System.out.println(toSay); sleep(1000); } } catch (InterruptedException e) { System.out.println(e); } }

Creating Threads Demo 1 16 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) public static void main(String [ ] args) { Output thr1 = new Output (“Hello”); Output thr2 = new Output (“There”); thr1.start(); thr2.start(); } Main thread is just another thread (happens to start first) Main thread can end before the others do Any thread can spawn more threads

Creating Threads Demo 2 17 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) class Output implements Runnable { private String toSay; public Output(String st) { toSay = st; } public void run() { try { for (int i=1; i<=2; i++) { // you can change the iteration as you want System.out.println(toSay); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(e); }}}

Creating Threads Demo 2 18 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) public static void main(String [ ] args) { Output out1 = new Output(“Hello”); Output out2 = new Output(“There”); Thread thr1 = new Thread(out1); Thread thr2 = new Thread(out2); thr1.start(); thr2.start(); }} Main is a bit more complex Everything else identical for the most part

Controlling Java Threads 19 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) start(): begins a thread running wait() and notify(): for synchronization stop(): kills a specific thread (deprecated) suspend() and resume(): deprecated join(): wait for specific thread to finish setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is default (NORM_PRIORITY)

yield() Method 20 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) yield() method used to temporarily release time for other threads public void run() { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); Thread.yield(); } }

sleep() Method 21 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) The sleep (long mills) method puts the thread to sleep for the specified time in milliseconds public void run() { for (int i = 1; i <= 60; i++) { System.out.print(" " + i); try { if (i >= 50) Thread.sleep(1); } catch (InterruptedException ex) { System.out.println(ex); }}}

sleep() Vs yield() Methods 22 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) There is a big difference Calling sleep put the current running thread into the blocked state Calling yield does not put the calling thread, t1 into the blocked state It merely let the scheduler kick in and pick another thread to run It might happen that the t1 is select to run again. This happens when t1 has a higher priority than all other runnable threads

join() Method 23 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) join() method used to force one thread to wait for another thread to finish public void run(){ Thread thread4 = new Thread(new PrintChar('c', 60)); thread4.start(); try { for (int i = 1; i < lastNum; i++){ System.out.print(" " + i); if (i == 50) thread4.join(); }} catch (InterruptedException ex) { System.out.println(ex); }}

isAlive(), interrupt(), and isInterrupt() 24 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) The isAlive() method is used to find out the state of a thread. It returns true if a thread is in the Ready, Blocked, or Running state; it returns false if a thread is new and has not started or if it is finished The interrupt() method interrupts a thread in the following way: If a thread is currently in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is awakened and enters the Ready state, and an java.io.InterruptedException is thrown The isInterrupt() method tests whether the thread is interrupted

Thread Priority 25 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Each thread is assigned a default priority of Thread.NORM_PRIORITY. You can reset the priority using setPriority (int priority) Some constants for priorities include Thread.MIN_PRIORITY, Thread.MAX_PRIORITY, Thread.NORM_PRIORITY

Thread Synchronization 26 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) Synchronization is prevent data corruption Synchronization allows only one thread to perform an operation on a object at a time If multiple threads require an access to an object, synchronization helps in maintaining consistency

The synchronized Keyword 27 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) To avoid resource conflicts, it is necessary to prevent more than one thread from simultaneously entering certain part of the program, known as critical region You can use the synchronized keyword to synchronize the method so that only one thread can access the method at a time A synchronized method acquires a lock before it executes. In the case of an instance method, the lock is on the object for which the method was invoked public synchronized void deposit (double amount)

Thread Prioritizing Demo 28 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) class Output extends Thread { private String toSay; public Output (String st) { toSay = st; } public void run() { try { for ( int i=1; i<=2; i++) { // you can change the iteration as you want System.out.println(toSay); sleep(1000); } } catch (InterruptedException e) { System.out.println(e); } }

Thread Prioritizing Demo 29 Lecture 3: Multithreading Concept 9/9/2019 Estifanos T. (MSc in Computer Networking) public static void main(String [ ] args) { Output thr1 = new Output (“Hello”); Output thr2 = new Output (“There”); thr1.setPriority (MIN_PRIORITY); thr2.setPriority (MAX_PRIORITY); thr1.start(); thr2.start(); }

End Of Chapter Three