slide3.4_2009_r1 - Module 3.4 Multithreading Multithreading...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 3.4 Multithreading Multithreading EE3206/EE5805 Java Programming & Applications 1 Intended Learning Outcomes Intended To understand the concept of multithreading To understand the life cycle of a thread. To To develop task classes by implementing the Runnable iinterface Runnable nterface in cases of multiple inheritance. in To create threads to run tasks using the Thread class. Thread To execute tasks in a thread pool. To To use synchronized methods or block to synchronize threads to avoid race conditions. avoid EE3206/EE5805 Java Programming & Applications 2 Threads Concept Threads Thread - Single sequential flow of control within a program Why threads? Need to handle concurrent tasks Like OS running multiple processes at the same time Sharing CPU time by multiple threads (managed by OS) Multiple threads on multiple CPUs Thread 1 Thread 2 Thread 3 Multiple threads sharing a single CPU Thread 1 Thread 2 Thread 3 EE3206/EE5805 Java Programming & Applications 3 Thread States Thread A thread can be in one of five states: New, Ready, Running, Blocked, or Finished. yield(), or time out Thread created New start() Ready run() Target finished Wait for target to finish join() sleep() wait() Finished Running run() returns Wait for time out Time out Wait to be notified notify() or notifyAll() Blocked interrupt() EE3206/EE5805 Java Programming & Applications 4 Introduction to Thread Class «interface» java.lang.Runnable +run(): void java.lang.Thread +Thread() +Thread(task: Runnable) +start(): void +isAlive(): boolean +setPriority(p: int): void +join(): void +sleep(millis: long): void +yield(): void +interrupt(): void Creates a default thread. Creates a thread for a specified task. Starts the thread that causes the run() method to be invoked by the JVM. 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. Interrupts this thread. EE3206/EE5805 Java Programming & Applications 5 Thread and Task Thread Thread Thread A Thread object represents a sequential flow of control. When a thread Thread object starts, it executes its run() method that declared by the Runnable interface. Runnable The default implementation of the run() method provided by the Thread The hread class is empty. So it does nothing and returns immediately. class 1) You can extends the Thread class and override the run() method. Thread 2) You can also assign a task to a thread to execute instead. 2) Task Task A task is an instance of Runnable. Runnable The Runnable interface contains an abstract method run(). Runnable You can create a task by defining a class that implements the run() You n() method. Put the code that you want to be executed by a thread into the method. to run() method. run() EE3206/EE5805 Java Programming & Applications 6 Execute a Task by a Thread Execute java.lang.Runnable TaskClass // Custom task class public class TaskClass implements Runnable { ... public TaskClass(...) { ... } // 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 TaskClass TaskClass task = new TaskClass(...); // Create a thread Thread thread = new Thread(task); // Start a thread thread.start(); ... } ... Create a task by implementing Runnable interface. Implement the run() method to tell what to do in this task. Create a thread object to execute a given task. The start() method of a thread, by default, invoke the run() method of the given task. 7 EE3206/EE5805 Java Programming & Applications Example: Using the Runnable Interface to Runnable Interface Create and Launch Threads Create Objective: Create and run three threads: Objective: The first thread prints the letter a 100 times. 100 The second thread prints the letter b 100 times. The third thread prints the integers 1 through 100. The Sample Output: aaaaaaaaaaaaaaaa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15bbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31bbbbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47bbbbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63bbbbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79bbbbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95bbbbbbbbbbbbbbbbaaaa 96 97 98 99 100bbbbbb TaskThreadDemo Run 8 EE3206/EE5805 Java Programming & Applications The static yield() Method The You can use the yield() method to temporarily release time for other threads. For example, temporarily for you may modify the run() method of PrintNum in the previous example as follows: PrintNum public void run() { for (int i = 1; i <= lastNum; i++) { 1; lastNum System.out.print(" " + i); Thread.yield(); } } Every time a number is printed, the thread3 (print100) is yielded. The two other threads then Every d. take the time to print characters. take Sample Output: aaaaaaaaaaaaaaaa 1bbbbbbbbbbbb 2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 3bbbbbbbbbbb bbbbbb 4aaaaaaaaaaaaaaaaa 5bbbbbbbbbbbbbbbbb 6aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabb bbbbbbbbbbbbbbbb 7bbbbbbbbbbbbbbbbbb 8bbbbbbbbbbbbbbbbbb 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7 0 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 EE3206/EE5805 Java Programming & Applications 9 The static sleep() Method The The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. For example, you may modify the run() method of PrintNum iin the previous PrintNum n example as follows: example public void run() { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); try { if (i >= 30) Thread.sleep(1); } catch (InterruptedException ex) { } } } Every time a number (>= 30) is printed, the thread3 (print100) is put to sleep for 1 millisecond. Sample Output: aaaaaaaaaaaaaaaa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15bbbbbbbbbbbbbbaaaaaaaaaaaaaa aa 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30bbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaa a 31bbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbb 32aaaaaaaaaaaaaaaaabbbbb bbbbbbbbbbbbaaaaaaaaaaaaaa 33bbbbbbbbbbbbbbbbbaaab 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7 0 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 EE3206/EE5805 Java Programming & Applications 10 The join() Method The You can use the join() method to force one thread to wait for another thread to finish. For You other example, you may modify the main() method of PrintNum in the previous example as follows: PrintNum // at the end of main for (int i = 1; i <= lastNum; i++) { 1; lastNum System.out.print(’c’); try { if (i == 10) if thread2.join(); thread2.join(); } catch (InterruptedException ex) { } } After printing 10 letter of c, it waits for thread2 (printB) to finished before printing again. After Sample Output: ccccc 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15bbbbbbbbbbbbbbaaaaaaaaaaaaaa 16 17 18 1 9 20 21 22 23 24 25 26 27 28 29 30 31cccccaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47aaaaaaaaaaaabbbbbbbbbbbbbbbb 48 49 5 0 51 52 53 54 55 56 57 58 59 60 61 62 63aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb 64 65 6 6 67 68 69 70 71 72 73 74 75 76 77 78 79aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb 80 81 8 2 83 84 85 86 87 88 89 90 91 92 93 94 95aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb 96 97 9 8 99 100aaaaaaaaabbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc EE3206/EE5805 Java Programming & Applications 11 Interrupt a Thread Interrupt The isAlive() method is used to find out the state of a thread. It returns isAlive() true iif a thread is in the Ready, Blocked, or Running state; it returns false iif true f false f a thread is in New or Finished state. New or Finished The interrupt() method interrupts a thread in the following way: The If a thread is currently in the Ready or Running state, its interrupted flag is set, but it Ready state, will not be aborted by this call. will The interrupted thread can use the method isInterrupted() to test whether itself is isInterrupted() being interrupted by others (see if interrupted flag is set). Thiis is usually done in the s being run( ) method of a thread. run( If a thread is currently Blocked, iit is awakened and enters the Ready state. It will Blocked t receive an java.io.InterruptedException and its interrupted flag will be cleared then. java.io.InterruptedException The interrupted thread can catch the InterruptedException and handle it accordingly. InterruptedException and For example, terminates itself. For EE3206/EE5805 Java Programming & Applications 12 Stopping a Thread Stopping A thread executes a task and stops when finishes the given task. The thread object then remains in memory in the Finished state and cannot be reused to execute other tasks Finished state anymore. anymore. It is a kind of waste that you need to create a new thread object for every task to execute. In the next section, you will see a better thread management approach. see EE3206/EE5805 Java Programming & Applications 13 Thread Priority Thread Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. executed Each thread is assigned a default priority of Thread.NORM_PRIORITY. You can reset the priority using Thread.NORM_PRIORITY You setPriority(int priority). setPriority(int Some constants for priorities include Thread.MIN_PRIORITY Thread.MIN_PRIORITY Thread.NORM_PRIORITY Thread.MAX_PRIORITY // 1 // 5 // 10 EE3206/EE5805 Java Programming & Applications 14 Thread Pools Thread Starting a new thread for each task could limit throughput and cause poor performance. A thread pool is ideal to manage the number of tasks executing concurrently. Java uses the Executor interface for executing tasks in a thread pool and; the ExecutorService interface for managing and controlling tasks. ExecutorService is a subinterface of Executor. «interface» java.util.concurrent.Executor +execute(Runnable object): void Executes the runnable task. «interface» java.util.concurrent.ExecutorService +shutdown(): void Shuts down the executor, but allows the tasks in the executor to complete. Once shutdown, it cannot accept new tasks. Returns true if the executor has been shutdown. Returns true if all tasks in the pool are terminated. +isShutdown(): boolean +isTerminated(): boolean EE3206/EE5805 Java Programming & Applications 15 Creating Executors Creating We are used to use the new operator to create an object from a certain class. For example, Fruit f1 = new Apple(); Fruit f2 = new Orange(); As you can see, the above example requires the user to know the underlying concrete classes (Apple and Orange). Java API adopts a design pattern – factory pattern that further abstracting the creation of an object. The static factory methods below are responsible for creating objects conforming to the Fruit. Fruit f1 = FruitFactory.newApple(); // static method Fruit f2 = FruitFactory.newOrange(); // static method To create an Executor object, use the static methods in the Executors class. The static methods return an object of ExecutorService while you do not know which concrete implementation is used. java.util.concurrent.Executors ExecutorDemo Run +newFixedThreadPool(numberOfThreads: Creates a thread pool with a fixed number of threads executing int): ExecutorService concurrently. A thread may be reused to execute another task after its current task is finished. +newCachedThreadPool(): Creates a thread pool that creates new threads as needed, but ExecutorService will reuse previously constructed threads when they are available. EE3206/EE5805 Java Programming & Applications 16 Thread Interference Thread 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 1 2 3 4 balance 0 0 1 1 thread[i] newBalance = bank.getBalance() + 1; newBalance = bank.getBalance() + 1; bank.setBalance(newBalance); bank.setBalance(newBalance); thread[j] EE3206/EE5805 Java Programming & Applications 17 Example: Showing Resource Conflict Example: Objective: Write a program that demonstrates the problem of resource conflict. Write ct. 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. penny AccountWithoutSync Run EE3206/EE5805 Java Programming & Applications 18 Race Condition Race Step 1 2 3 4 ); balance 0 0 1 1 Task 1 newBalance = balance + 1; Task 2 newBalance = balance + 1; balance = newBalance; balance = newBalance; Here is a possible scenario of the preceding example: Here The effect of this scenario is that Task 1 did nothing, because in Step 4 Task 2 overwrites Task 1's result. Obviously, the problem is that Task 1 and Task 2 are accessing a common resource in a way that causes conflict. This is a common problem known as race resource This condition or thread interference in multithreaded programs. condition A class is said to be thread-safe iif an object of the class does not cause a race f thread condition in the presence of multiple threads. As demonstrated in the preceding condition the example, the Account class is not thread-safe. example, safe. EE3206/EE5805 Java Programming & Applications 19 Synchronized Methods Synchronized The common resource accessed by multiple threads are known as critical region. More critical More than one thread must be prevented from simultaneously entering the critical region of a program. To avoid resource conflicts, Java uses the keyword synchronized to declare a synchronized to synchronized method. synchronized The critical region in the previous example is the entire deposit method. You can add the keyword synchronized to the method synchronized to header. As a result, only one thread can access the method at a time, and hence Account becomes thread-safe. Account public synchronized void public synchronized void deposit(double amount) { deposit(double // method body } With the deposit method synchronized, the preceding scenario cannot happen. If Task 2 starts to enter the method, and Task 1 is already in the method, Task 2 is blocked until Task 1 finishes the method. blocked Task 1 Acquire a lock on the object account Task 2 Execute the deposit method Wait to acquire the lock Release the lock Acqurie a lock on the object account Execute the deposit method Release the lock AccountWithSync Run 20 EE3206/EE5805 Java Programming & Applications ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online