Multi-threaded applications SE-28111. SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.

Slides:



Advertisements
Similar presentations
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Advertisements

Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Multithreading The objectives of this chapter are:
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Week 3, Day 1: Processes & Threads Return Quiz Processes Threads Lab: Quiz Lab 3: Strategy & Factory Patterns! SE-2811 Slide design: Dr. Mark L. Hornick.
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)
Week 3, Day 1: Processes & Threads Processes Threads SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
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.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Processes, Threads, and Process States. Programs and Processes  Program: an executable file (before/after compilation)  Process: an instance of a program.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
A running program is a collection of “threads” – essentially independent execution streams When the main() method is called, the instructions within.
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 & 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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Multithreading The objectives of this chapter are:
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Multithreading.
SE-2811 Software Component Design
Chapter 19 Java Never Ends
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
SE /11/2018 If you think the internet is not working in its current incarnation, you can’t change the system through think-pieces and F.C.C. regulations.
Multithreading.
Multithreading 2 Lec 24.
Multithreading.
Multithreaded Programming
9. Threads SE2811 Software Component Design
Multithreading in java.
Threads and Multithreading
9. Threads SE2811 Software Component Design
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multi-threaded applications SE-28111

SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions within the method begin to execute in sequence The program terminates when the main() method finishes executing Is this really true? Sometimes it is….

SE-2811 Dr. Mark L. Hornick 3 The ugly truth… When the main() method is called, the instructions within the method begin to execute in sequence on the primary thread The program terminates when the primary thread, and any additional threads, finish executing

What’s a Thread? First, let’s define Process: A Process is most easily understood as a program or application running on your PC A process generally has a complete, private set of basic run-time resources, in particular: Its own memory space Execution priority A list of Threads that execute within it A set of credentials with which to execute (usually yours); this provides authorization to access various resources, such as files SE-28114

By default, a Process creates and executes a single primary Thread BUT: A Process can create and execute more than one Thread The JVM works with the OS to create Processes and Threads The underlying OS provides the essential multiprocessing support SE-28115

Modern operating systems are all capable of running multiple Processes simultaneously (On single-CPU PC’s) each Process runs individually for a discrete time period while one Process runs, other Processes sleep The Process currently executing changes very rapidly - every few milliseconds Operating systems use a Scheduler (basically, an ISR that executes on a timer interrupt) to distribute CPU time among Processes The net effect is that you (the user) observe all processes running simultaneously and continuously SE-28116

When you run a Java application, the JVM creates a Process and a Primary Thread The Primary Thread begins executing the main() method in the main class Note: other java programs, like applets, begin execution with an init() method If no other Threads are created, the Process terminates when the Primary Thread terminates That is, when there are no more instructions to execute on that Thread SE-28117

Threads wind their way through the code until they run out of instructions to execute public class App{ public static void main(String[] args) { App me = new App(); me.method_A(); } private void method_A() { // more code here method_B(); return; } private void method_B() { return; } private void method_C() { // more code here } SE-28118

Where do other Threads come from? 1. You implicitly create additional Threads when you write a Swing-based application Java applications that create and display windows cause Swing to create additional threads 2. You implicitly create additional Threads when you use various Java utility classes Using the Timer class causes a Thread to be created 3. You can explicitly create additional Threads and control their execution SE-28119

You already know how to create a multi-threaded app using Swing 1. Create a JFrame window containing JButtons, JTextField, etc. 2. Connect the JButtons etc to an ActionListener 3. Make the window visible Once the window is visible, a second Thread is created All calls to actionPerformed() occur on the second Thread The Event-Dispatching Thread SE-2811 Dr. Mark L. Hornick 10

Using a Timer is fairly straighforward: Timer timer = new Timer(timeoutPeriod, eventHandler); timer.start(); The eventHandler argument to the constructor is a reference to a class that implements Timer ActionListener That is, eventHandler contains an actionPerformed() method. This is similar to how Swing events are handled Whenever the Timer generates a timeout event, the JVM invokes actionPerformed() on another thread JVM uses the Event Dispatch thread when available; otherwise a “worker” thread is created SE-2811 Dr. Mark L. Hornick 11

Explicitly creating additional Threads is pretty easy: Thread t = new Thread( r ); t.start(); The r argument to the Thread constructor is a reference to a class that implements the Runnable interface Runnable declares a single method: public void run() When the Thread’s start() method is called, the instructions in the run() method begin executing on the new thread. The start() method returns essentially immediately; it does not wait for the started thread to finish execution. SE

The main class may implement the Runnable interface itself: public class App implements Runnable{ public static void main(String[] args) { App me = new App(); me.method_A(); } private void method_A() { // more code here method_B(); return; } private void method_B() { Thread t = new Thread(this); // App is runnable! t.start(); // start executing the run() method return; } public void run() { // more code here } SE

Both threads execute simultaneously and independently after the secondary thread is started public class App implements Runnable{ public static void main(String[] args) { App me = new App() me.method_A(); } private void method_A() { // more code here method_B(); return } private void method_B() { Thread t = new Thread(this); t.start();// execute run() on new thread return; } public void run() { // more code here } SE

The secondary thread may execute a method defined in another class that implements Runnable public class App { public static void main(String[] args) { App me = new App(); me.method_A(); } private void method_A() { ThreadRunner tr = new ThreadRunner(); Thread t = new Thread(tr); t.start(); return; } private class ThreadRunner implements Runnable { // inner class public void run() { // more code here } SE

An anonymous inner class is another typical approach… public class App { public static void main(String[] args) { App me = new App(); me.method_A(); } private void method_A() { Thread t = new Thread( new Runnable() { public void run() { // more code here } } ); t.start(); return; } SE

An application may be designed to execute the same instructions on more than one thread at the same time public class App implements Runnable { public static void main(String[] args) { App me = new App() me.method_A(); } private void method_A() { ThreadRunner tr = new ThreadRunner(); Thread t = new Thread(tr); t.start(); // execute run() on new secondary thread method_C(); // execute method_C on the primary thread } private void method_C() { // more code here } public void run() { // some other instructions here method_C(); // execute method_C on the secondary thread method_C(); // execute method_C on the secondary thread } SE

Question: Is it a good idea to let two (or more) threads execute the same code at the same time? SE

Fortunately, Java supports several mechanisms for synchronizing the execution of multiple threads SE Keeping code thread-safe

The Thread class’s join() method is one way of synchronizing two threads: Thread t = new Thread(cref); t.start(); t.join(); // wait for 2 nd thread to finish… method_C(); // …before executing next inst. The second Thread starts executing the instructions in the run() method. The current thread (the launcher of the second thread) waits until the second thread finishes SE

If a method is declared to be synchronized, it will only be run on a single thread at a time public class App implements Runnable { public static void main(String[] args) { App me = new App() me.method_A(); } private void method_A() { ThreadRunner tr = new ThreadRunner(); Thread t = new Thread(tr); t.start(); method_C(); // run method_C on the primary thread } private synchronized void method_C() { // More code here } public void run() { // some other instructions here method_C(); // run method_C on the secondary thread method_C(); // run method_C on the secondary thread } SE

Once a thread enters a synchronized method, no other threads can enter until the first thread completes execution of the method, and exits the method. private synchronized void method_C() { } SE Thread x Thread yThread z When Thread x leaves the method, the Scheduler arbitrarily allows one of the other threads to enter the method. When the second thread exits, the Scheduler allows another waiting thread to enter. If all threads get to the method at the same time, the thread that gets to enter the method first is determined arbitrarily by the Scheduler.

Is synchronized the solution to everything? Can you think of any disadvantage to making a method synchronized? SE

If only a few statements within a method need to be guarded against simultaneous execution, use a synchronized block instead of making the entire method synchronized. private void method_C() { synchronizedsync_object synchronized( ) { } } SE Thread x Thread yThread z When Thread x leaves the block, the Scheduler arbitrarily allows one of the other threads to enter.

The synchronizing object can be any object Java’s Object class incorporates the concept of something called a Monitor Monitors are used to guard the gates of synchronized blocks Monitors only become active within a synchronized block SE

Since every class derives from Object, the class containing a synchronized block can act as the Monitor for the block: private void method_C() { synchronized( this ) { // gate down }// gate up }// gate up } SE Thread x Thread yThread z

Or any generic Object can act as a Monitor private Object guard = new Object(); private Object guard = new Object(); private void method_C() { guard synchronized( guard ) { // gate down } // gate up } SE Thread x Thread yThread z

Consider the following code. Suppose all threads reach the for() loop simultaneously. How do the threads compete to run the for() loop? private Object guard = new Object(); private void method_C() { for( int i=0; i<100; i++ ) { synchronized( guard ) { // gate down } // gate up } // gate up } // end for } SE Thread x Thread yThread z

After each thread executes the synchronized section, it can notifiy the Monitor that another thread can be allowed to enter the synchronized block as soon as it relinquishes ownership of the synchronized section by entering a wait (or exiting the synchronized section) private Object guard = new Object(); private void method_C() { for( int i=0; i<100; i++ ) { synchronized( guard ) { // gate down guard.notify(); // signal waiting threads guard.wait(); // wait for other threads guard.wait(); // wait for other threads } } // end for } SE Thread x Thread yThread z