Chapter 19 Multithreading

Similar documents
Chapter 32 Multithreading and Parallel Programming

CPIT 305 Advanced Programming Multithreading

Multithread Computing

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Buch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: , 23:59

Introduction to Java Threads

Chapter 32. Multi-threading

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

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

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

Object Oriented Programming. Week 10 Part 1 Threads

7. MULTITHREDED PROGRAMMING

Threads Chate Patanothai

Java Threads. COMP 585 Noteset #2 1

Multithreaded Programming

Threads Questions Important Questions

Animation Part 2: MoveableShape interface & Multithreading

Unit - IV Multi-Threading

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

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

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Multithreaded Programming

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

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

Concurrent Programming using Threads

Threads in Java (Deitel & Deitel)

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Advanced Concepts of Programming

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

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

CMSC 330: Organization of Programming Languages

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

Synchronized Methods of Old Versions of Java

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

Java Threads. Introduction to Java Threads

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

Basics of. Multithreading in Java

G52CON: Concepts of Concurrency

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

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

Multithreading in Java Part 2 Thread - States JAVA9S.com

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Module - 4 Multi-Threaded Programming

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

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

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

Performance Throughput Utilization of system resources

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Software Practice 1 - Multithreading

CS 556 Distributed Systems

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

CS11 Java. Fall Lecture 7

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

UNIT V CONCURRENT PROGRAMMING

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

public class Shared0 { private static int x = 0, y = 0;

Multi-threading in Java. Jeff HUANG

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Threads and Java Memory Model

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

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

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

Amity School of Engineering

Only one thread can own a specific monitor

CERTIFICATION OBJECTIVES

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

CSCD 330 Network Programming

CSCD 330 Network Programming

Unit 5 - Exception Handling & Multithreaded

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS

Info 408 Distributed Applications Programming Exercise sheet nb. 4

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

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

Programming Java. Multithreaded Programming

Concurrent Programming

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Unit III Rupali Sherekar 2017

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

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

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

Synchronization

CS180 Review. Recitation Week 15

Multi-Threaded Concurrency in Java

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

04-Java Multithreading

CS 351 Design of Large Programs Threads and Concurrency

Programming Language Concepts: Lecture 11

Advanced Programming Concurrency

15CS45 : OBJECT ORIENTED CONCEPTS

CS 159: Parallel Processing

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

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

Overview of Java Threads (Part 2)

Transcription:

Chapter 19 Multithreading Prerequisites for Part VI Chapter 14 Applets, Images, and Audio Chapter 19 Multithreading Chapter 20 Internationalization 1

Objectives To understand the concept of multithreading and apply it to develop animation ( 19.2). To develop thread classes by extending the Thread class ( 19.3). To develop thread classes by implementing the Runnable interface in cases of multiple inheritance ( 19.4). To describe the life-cycle of thread states and set thread priorities ( 19.4). To know how to control threads: starting, stopping, suspending, and resuming threads ( 19.4). To use synchronized methods or block to synchronize threads to avoid race conditions ( 19.7.1). To use wait(), notify(), and notifyall() to facilitate thread cooperation ( 19.7.3). To use the resource ordering technique to avoid deadlock ( 19.7.4). To control animation using threads ( 19.8 Optional). To play audio clips on separate threads ( 19.9 Optional). To display the completion status of a task using JProgressBar ( 19.10 Optional). 2

Threads Concept Multiple threads on multiple CPUs Multiple threads sharing a single CPU Thread 1 Thread 2 Thread 3 Thread 1 Thread 2 Thread 3 3

Creating Threads by Extending the Thread class // Custom thread class public class CustomThread extends Thread {... public CustomThread(...) {... java.lang.thread CustomThread // Override the run method in Thread public void run() { // Tell system how to run custom thread...... // Client class public class Client {... public void somemethod() {... // Create a thread CustomThread thread1 = new CustomThread(...); // Start a thread thread1.start();... // Create another thread CustomThread thread2 = new CustomThread(...); // Start a thread thread2.start();... 4

Example 19.1 Using the Thread Class to Create and Launch Threads Objective: Create and run three threads: The first thread prints the letter a 100 times. The second thread prints the letter b 100 times. The third thread prints the integers 1 through 100. TestThread Run 5

Creating Threads by Implementing the Runnable Interface // Custom thread class public class CustomThread implements Runnable {... public CustomThread(...) {... java.lang.runnable CustomThread // Implement the run method in Runnable public void run() { // Tell system how to run custom thread...... // Client class public class Client {... public void somemethod() {... // Create an instance of CustomThread CustomThread customthread = new CustomThread(...); // Create a thread Thread thread = new Thread(customThread); // Start a thread thread.start();...... 6

Example 19.2 Using the Runnabel Interface to Create and Launch Threads Objective: Create and run three threads: The first thread prints the letter a 100 times. The second thread prints the letter b 100 times. The third thread prints the integers 1 through 100. TestRunnable Run 7

The Thread Class java.lang.runnable java.lang.thread +Thread(tagert: Runnable) +run(): void +start(): void +interrupt(): void +isalive(): boolean +setpriority(p: int): void +join(): void +sleep(millis: long): void +yield(): void +isinterrupted(): Boolean +currentthread(): Thread Creates a new thread to run the target object. Invoked by the Java runtime system to execute the thread. You must override this method and provide the code you want your thread to execute in your thread class. This method is never directly invoked by the runnable object in a program, although it is an instance method of a runnable object. Starts the thread that causes the run() method to be invoked by the JVM. Interrupts this thread. If the thread is blocked, it is ready to run again. Tests whether the thread is currently running. Sets priority p (ranging from 1 to 10) for this thread. Waits for this thread to finish. Puts the runnable object to sleep for a specified time in milliseconds. Causes this thread to temporarily pause and allow other threads to execute. Tests whether the current thread has been interrupted. Returns a reference to the currently executing thread object. 8

The Static yield() Method You can use the yield() method to temporarily release time for other threads. For example, suppose you modify the code in Lines 57-58 in TestRunnable.java in Example 19.2 as follows: public void run() { for (int i = 1; i <= lastnum; i++) { System.out.print(" " + i); Thread.yield(); Every time a number is printed, the print100 thread is yielded. So, the numbers are printed after the characters. 9

The Static sleep(milliseconds) Method The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. For example, suppose you modify the code in Lines 56-60 in TestRunnable.java in Example 19.2 as follows: public void run() { for (int i = 1; i <= lastnum; i++) { System.out.print(" " + i); try { if (i >= 50) Thread.sleep(1); catch (InterruptedException ex) { Every time a number (>= 50) is printed, the print100 thread is put to sleep for 1 millisecond. 10

The join() Method You can use the join() method to force one thread to wait for another thread to finish. For example, suppose you modify the code in Lines 56-60 in TestRunnable.java in Example 19.2 as follows: public void run() { for (int i = 1; i <= lastnum; i++) { System.out.print(" " + i); try { if (i == 50) printa.join(); catch (InterruptedException ex) { The numbers after 50 are printed after thread printa is finished. 11

The wait(), notify(), and notifyall() Method The wait(), notify(), and notifyall() methods defined in the Object class are also used with threads to facilitate communications among the active threads: While the join() method forces one thread to wait for another thread to finish, the wait(), notify(), and notifyall() are used to synchronize among the active threads, as shown in Figure 19.7. More detail on these methods is discussed in Section 19.7.3, Cooperation Among Threads. Thread t1 Thread t2 Thread t1 Thread t2 Wait for t2 to finish t2.join() Wait for notification anobj.wait() anobj.notify() t2 finished (A) Using the join() method (B) Using the wait(), notify(), or notifyall() 12

Thread States A thread can be in one of five states: New, Ready, Running, Blocked, or Finished. Thread created New start() Ready yield(), or time out run() join() Running run() returns Finished Target finished interrupt() sleep() wait() Wait for target to finish Wait for time out Wait to be notified Blocked Time out notify() or notifyall() Interrupted() 13

isalive(), interrupt(), and isinterrupted() 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. 14

The deprecated stop(), suspend(), and resume() Methods NOTE: The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods are deprecated (or outdated) because they are known to be inherently unsafe. You should assign null to a Thread variable to indicate that it is stopped rather than use the stop() method. 15

Thread Priority 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 16

Thread Groups Construct a thread group using the ThreadGroup constructor: ThreadGroup g = new ThreadGroup("timer thread group"); Place a thread in a thread group using the Thread constructor: Thread t = new Thread(g, new ThreadClass(), "This thread"); 17

Thread Groups, cont. To find out how many threads in a group are currently running, use the activecount() method: System.out.println("The number of + runnable threads in the group + g.activecount()); 18

Synchronization A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict. Step balance thread[i] thread[j] 1 0 newbalance = bank.getbalance() + 1; 2 0 newbalance = bank.getbalance() + 1; 3 1 bank.setbalance(newbalance); 4 1 bank.setbalance(newbalance); 19

Example 19.3 Showing Resource Conflict Objective: Write a program that demonstrates the problem of resource conflict. Suppose that you create and launch one hundred threads, each of which adds a penny to an account. Assume that the account is initially empty. java.lang.thread java.lang.object java.lang.object AddAPennyThread 100 1 1 1 AccountWithoutSync Account +run(): void -bank: Account -thread: Thread[] +main(args: String[]): void -balance: int +getbalance(): int +deposit(amount: int): void AccountWithoutSync Run 20

Race Condition What, then, caused the error in Example 19.3? Here is a possible scenario: Step balance thread[i] thread[j] 1 0 newbalance = balance + 1; 2 0 newbalance = balance + 1; 3 1 balance = newbalance; 4 1 balance = newbalance; ) The effect of this scenario is that thread thread[i] did nothing, because in Step 4 thread thread[j] overrides thread[i]'s result. Obviously, the problem is that thread[i] and thread[j] are accessing a common resource in a way that causes conflict. This is a common problem known as a race condition in multithreaded programs. A class is said to be thread-safe if an object of the class does not cause a race condition in the presence of multiple threads. As demonstrated in the preceding example, the Account class is not thread-safe. 21

The synchronized keyword To avoid resource conflicts, Java uses the To avoid race conditions, more than one thread must be prevented from simultaneously entering certain part of the program, known as critical region. The critical region in Example 19.3 is the entire deposit method. You can use the synchronized keyword to synchronize the method so that only one thread can access the method at a time. There are several ways to correct the problem in Example 19.3, one approach is to make Account thread-safe by adding the synchronized keyword in the deposit method in Line 45 as follows: public synchronized void deposit(double amount) 22

Synchronizing Instance Methods and Static Methods 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. In the case of a static method, the lock is on the class. If one thread invokes a synchronized instance method (respectively, static method) on an object, the lock of that object (respectively, class) is acquired first, then the method is executed, and finally the lock is released. Another thread invoking the same method of that object (respectively, class) is blocked until the lock is released. 23

Synchronizing Instance Methods and Static Methods With the deposit method synchronized, the preceding scenario cannot happen. If thread thread[j] starts to enter the method, and thread thread[i] is already in the method, thread thread[j] is blocked until thread thread[i] finishes the method. thread[i] thread[j] Acqurie a lock on the object bank Execute the deposit method Release the lock Wait to acquire the lock Acqurie a lock on the object bank Execute the deposit method Release the lock 24

Synchronizing Statements Invoking a synchronized instance method of an object acquires a lock on the object, and invoking a synchronized static method of a class acquires a lock on the class. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block. The general form of a synchronized statement is as follows: synchronized (expr) { statements; The expression expr must evaluate to an object reference. If the object is already locked by another thread, the thread is blocked until the lock is released. When a lock is obtained on the object, the statements in the synchronized block are executed, and then the lock is released. 25

Synchronizing Statements vs. Methods Any synchronized instance method can be converted into a synchronized statement. Suppose that the following is a synchronized instance method: public synchronized void xmethod() { // method body This method is equivalent to public void xmethod() { synchronized (this) { // method body 26

Cooperation Among Threads Use the wait(), notify(), and notifyall() methods to facilitate communication among threads. The wait(), notify(), and notifyall() methods must be called in a synchronized method or a synchronized block on the calling object of these methods. Otherwise, an IllegalMonitorStateException would occur. The wait() method lets the thread wait until some condition occurs. When it occurs, you can use the notify() or notifyall() methods to notify the waiting threads to resume normal execution. The notifyall() method wakes up all waiting threads, while notify() picks up only one thread from a waiting queue. 27

Cooperation Among Threads Thread 1 Thread 2 synchronized (anobject) { try { // Wait for the condition to become true while (!condition) resume anobject.wait(); // Do something when condition is true catch (InterruptedException ex) { ex.printstacktrace(); synchronized (anobject) { // When condition becomes true anobject.notify(); or anobject.notifyall();... A synchronization lock must be obtained on the object to be waited or notified. When wait() is invoked, it pauses the thread and simultaneously releases the lock on the object. When the thread is restarted after being notified, the lock is automatically reacquired. 28

Example 19.4 Thread Cooperation Write a program that demonstrates thread cooperation. Suppose that you create and launch two threads, one deposits to an account, and the other withdraws from the same account. The second thread has to wait if the amount to be withdrawn is more than the current balance in the account. Whenever new fund is deposited to the account, the first thread notifies the second thread to resume. If the amount is still not enough for a withdrawal, the second thread has to continue to wait for more fund in the account. Assume the initial balance is 0 and the amount to deposit and to withdraw is randomly generated. ThreadCooperation Run 29

Deadlock Sometimes two or more threads need to acquire the locks on several shared objects. This could cause deadlock, in which each thread has the lock on one of the objects and is waiting for the lock on the other object. Consider the scenario with two threads and two objects, as shown in Figure 19.15. Thread 1 acquired a lock on object1 and Thread 2 acquired a lock on object2. Now Thread 1 is waiting for the lock on object2 and Thread 2 for the lock on object1. The two threads wait for each other to release the in order to get the lock, and neither can continue to run. Step Thread 1 Thread 2 1 2 3 4 5 6 synchronized (object1) { // do something here synchronized (object2) { // do something here synchronized (object2) { // do something here synchronized (object1) { // do something here Wait for Thread 2 to release the lock on object2 Wait for Thread 1 to release the lock on object1 30

Preventing Deadlock Deadlock can be easily avoided by using a simple technique known as resource ordering. With this technique, you assign an order on all the objects whose locks must be acquired and ensure that each thread acquires the locks in that order. For the example in Figure 19.15, suppose the objects are ordered as object1 and object2. Using the resource ordering technique, Thread 2 must acquire a lock on object1 first, then on object2. Once Thread 1 acquired a lock on object1, Thread 2 has to wait for a lock on object1. So Thread 1 will be able to acquire a lock on object2 and no deadlock would occur. 31

Controlling Animation Using Threads Section 12.6, The Timer Class, introduced how to control animations using the Timer class. You can also use a thread to control animations. Let us write an applet that displays a running clock. Use two buttons to suspend and resume the clock. 32

Implementation Using Threads Runnable StillClock JPanel ActionListener JApplet Clock +Clock() +run(): void +suspend(): void +resume(): void 1 1 1 1 ClockControl -clock: Clock jbtresume: JButton -jbtsuspend: JButton +ClockControl() +actionperformed(e: ActionEvent): void ClockApp +AppletClock() +main(args: String[]): void Clock ClockControl ClockApp Run 33

Running Audio on a Separate Thread When developing animation programs with audio, you should run audio on a separate thread to avoid delay in animation. To illustrate the problem, let us first write a program without playing audio on a separate thread. The program creates an applet that displays a running clock and announces the time at one-minute intervals. For example, if the current time is 6:30:00, the applet announces, "The time is six-thirty a.m." If the current time is 20:20:00, the applet announces, "The time is eight-twenty p.m." Also add a label to display the digit time. ClockWithAudio Run 34

Running Audio on a Separate Thread, cont. When you run the preceding program, you would notice that the second hand did not display at the first, second, and third seconds of the minute. This is because sleep(1500) was invoked twice in the announcetime() method, which takes three seconds to announce the time at the beginning of each minute. Thus, the actionperformed method is delayed for three seconds during the first three seconds of each minute. As a result of this delay, the time is not updated and the clock was not repainted for these three seconds. To avoid the conflict, you should announce the time on a separate thread. ClockWithAudioOnSeparateThread Run 35

JProgressBar JProgressBar is a component that displays a value graphically within a bounded interval. A progress bar is typically used to show the percentage of completion of a lengthy operation; it comprises a rectangular bar that is "filled in" from left to right horizontally or from bottom to top vertically as the operation is performed. It provides the user with feedback on the progress of the operation. For example, when a file is being read, it alerts the user to the progress of the operation, thereby keeping the user attentive. JProgressBar is often implemented using a thread to monitor the completion status of other threads. The progress bar can be displayed horizontally or vertically, as determined by its orientation property. The minimum, value, and maximum properties determine the minimum, current, and maximum length on the progress bar, as shown in Figure 9.20. minimum value maximum percentcomplete = value / maximum 36

javax.swing.jcomponent javax.swing.jprogressbar JProgressBar Methods +JProgressBar() +JProgressBar(min: int, max: int) +JProgressBar(orient: int) +JProgressBar(orient: int, min: int, max: int) +getmaximum(): int +setmaximum(n: int): void +getminimum(): int +setminimum(n: int): void +getorientation(): int +setorientation(orient: int): void +getpercentcomplete():double +getvalus(): int +setvalus(n: int): void +getstring(): String +setstring(s: String): void +isstringpainted(): Boolean +setstringpainted(b: boolean): void Creates a horizontal progress bar with min 0 and max 100. Creates a horizontal progress bar with specified min and max. Creates a progress bar with min 0 and max 100 and a specified orientation. Creates a progress bar with a specified orientation, min, and max. Gets the maximum value. (default: 100) Sets a new maximum value. Gets the minimum value. (default: 0) Sets a new minimum value. Gets the orientation value. (default: HORIZONTAL) Sets a new minimum value. Returns the percent complete for the progress bar. 0 <= a value <= 1.0. Returns the progress bar's current value Sets the progress bar's current value. Returns the current value of the progress string. Sets the value of the progress string. Returns the value of the stringpainted property. Sets the value of the stringpainted property, which determines whether the progress bar should render a progress percentage string. (default: false) 37

Example 19.7 JProgressBar Demo Objective: Write a GUI application that lets you copy files. A progress bar is used to show the progress of the copying operation, as shown in Figure 9.22. CopyFile Run 38