1 / 36

Multithreading

CPIT 305 Advance Programming. Multithreading. CPIT 305 Advance Programming. Outline: Introduction What are Threads ? Creating threads Using threads (starting and stopping) Some Basic Methods Life Cycle of thread Race Condition. CPIT 305 Advance Programming. Introduction.

bcallaghan
Download Presentation

Multithreading

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPIT 305 Advance Programming Multithreading

  2. CPIT 305 Advance Programming Outline: • Introduction • What are Threads ? • Creating threads • Using threads (starting and stopping) • Some Basic Methods • Life Cycle of thread • Race Condition

  3. CPIT 305 Advance Programming Introduction • Multitasking, in operating system, is allowing the user to perform more than one task on computer (such as printing, browsing internet and working on the word processor) at what seems like the same time. • The operating system is able to keep track of where you are in these tasks and go from one task to another without losing information.

  4. CPIT 305 Advance Programming Introduction Single processor System Multi processors System

  5. CPIT 305 Advance Programming What are Threads ? • Multithreadingis the ability of an application to manage its use by more than one user at a time and to even manage multiple requests by the same user • Therefore, it extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual threads.

  6. CPIT 305 Advance Programming What are Threads ? • Each task is going to be a thread with a separate identity, • and the programs that can run more than one thread at once are said to be multithreaded.

  7. CPIT 305 Advance Programming Creating Threads • In the Java there are two ways of creating threads: • extending the java.lang.Thread class • implementing the java.lang.Runnable interface

  8. CPIT 305 Advance Programming Creating Threads 1- extending the Thread class: import java.lang.*; public class AnyName extends Thread { public void run() { task code; } }

  9. CPIT 305 Advance Programming Creating Threads 2- implementing Runnable interface import java.lang.*; public class AnyName implements Runnable { Thread t; public void run() { …task code; } } • That interface is very simple, with a single abstract method: package java.lang; public interface Runnable { public abstract void run(); }

  10. CPIT 305 Advance Programming Creating Threads • The only difference between the two ways is that by implementing Runnable interface, there is greater flexibility in the creation of the class as the opportunity still exist for that class to extend from another class

  11. CPIT 305 Advance Programming Using Threads • In case you define thread as implement of Runnable Interface you can use this thread as follows: • In the main method: • Construct an object of your class: Runnable task = new AnyName(); • Construct a Thread object from the Runnable: Thread thread = new Thread(task); • Start the thread: thread.start();

  12. CPIT 305 Advance Programming Example 1 • Single Thread Example in the text file

  13. CPIT 305 Advance Programming Some Basic Methods of Thread • Thread currentThread() static method returns a reference to the currently executing thread. • String getName( ) method returns the name of the thread. • void setName(String name) method changes the name of this thread to be equal to the argument name.

  14. CPIT 305 Advance Programming Some Basic Methods of Thread • Thread.sleep( ) method pauses execution of the current thread for specific period of time (in milliseconds) and switches to the another threads to execute it. • Note that it is important to sleep somewhere in a thread. If not, the thread may consume all CPU time for the process and will not allow any other threads to be executed.

  15. CPIT 305 Advance Programming Example 2 • Multiple Threads Example in the text file • Simple Exercise: Modify the above program by implementing Runnable interface.

  16. CPIT 305 Advance Programming Exercise 1: • Create and run three threads: • The first thread prints the letter a 10 times. • The second thread prints the letter b 10 times. • The third thread prints the integers from 1 to 10. • Use Runnable interface to create and run the threads

  17. CPIT 305 Advance Programming Some Basic Methods of Thread • void join() method is used to tell other threads to wait until the thread on which it’s called terminates. • booleanisAlive() method return true if the thread on which it’s called is still running, otherwise it return false.

  18. CPIT 305 Advance Programming Example 3 • The same code as Example 2 but with join() and isAlive() methods • What do you notice ?

  19. CPIT 305 Advance Programming Exercise 2 • In the Exercise 1, create ‘thread4’ Thread to print the character ‘c’ 4 times • Your code should force the thread3 to print the numbers from 5 to 10 after the new thread is finished

  20. CPIT 305 Advance Programming Thread Termination Thread is terminated when: • Executing the last statement in the body of Run method. • An exception occurs that is not caught in the method. Also, There is a way to forcea thread to terminate. the interrupt method can be used to requesttermination of a thread. • void interrupt() sends an interrupt request to a thread. The interrupted status of the thread is set to true. If the thread is currently blocked by a call to sleep or join, then an InterruptedException is thrown.

  21. CPIT 305 Advance Programming Some Basic Methods of Thread • booleanisInterrupted() method to find out whether the interrupted status was set. • However, if a thread is in the blocked state, it cannot check the interrupted status. This is where the InterruptedException comes in. • When the interrupt method is called by a thread that is in blocked state (cause sleep or wait), the blocking call is terminated by an InterruptedException.

  22. CPIT 305 Advance Programming Thread States (Life Cycle of threads)

  23. CPIT 305 Advance Programming Thread States (Life Cycle of threads) • New: a thread is begin its life cycle in the new state. It remains in this state until the start () method is called on it. • Runnable: After invocation of start() method on new thread, the thread becomes runnable and it will wait its order to execute • Running: A thread is running when it’s selected by thread scheduler to run • Waiting: A thread is waiting for another thread to perform a task, in this stage the thread is still alive • Terminated: a thread enter the terminated state when it complete its task

  24. CPIT 305 Advance Programming Race Condition • At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time • Otherwise, the conflict or corrupted for the shared resource may occur if it is accessed simultaneously by multiple threads.

  25. CPIT 305 Advance Programming Race Condition • For example, if two unsynchronized threads accessing the same bank account may cause conflict on the final balance amount • This problem is called Race Condition. 00 00

  26. CPIT 305 Advance Programming Synchronized / Lock and Unlock • To avoid race conditions, more than one thread must be prevented from simultaneously entering certain part of the program, known as critical region. • There are two mechanisms for protecting a code block from concurrent access: • A synchronized keyword: • synchronizedmethod. • synchronizedblock. • Explicit Lock and Condition.

  27. CPIT 305 Advance Programming Java synchronized Keyword • It is an essential tool in concurrent programming in Java. • Its overall purpose is to allow for only one thread at a timeto access into a particular section of code thus allowing us to protect variables or data from being corrupted by simultaneous modifications from different threads.

  28. CPIT 305 Advance Programming synchronized method • It marks a method that can be executed by only one thread at a time, using synchronized keyword along with method.

  29. CPIT 305 Advance Programming synchronized block • Using synchronized block in java is also similar to using synchronized methods. • synchronized block in Java is preferred over method synchronization because by using synchronized block , you only need to lock the critical section of code instead of whole method.

  30. CPIT 305 Advance Programming Exercise 3 • Write a Bank program that have multiple accounts with 1000 amount in each account, • You have to create threads that: • Allow users to transfer specific value from account to another account • Allow users to display the final amount in each or specific account • You may create Bank class that have the needed methods (transfer method and display method

  31. CPIT 305 Advance Programming Exercise 3 • Use the synchronization mechanism to make the threads use the function exclusively,, • Use synchronized method • Then, use synchronized block

  32. CPIT 305 Advance Programming Explicit Lock • A synchronized instance method implicitly acquires a lock on the instance before it executes the method. • An explicit lock is a tool provided by java for controlling access to a shared resource by multiple threads. • Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all threads that need to access to the shared resource require that lock to be released first.

  33. CPIT 305 Advance Programming Explicit Lock • Some important interfaces and classes in java.util.concurrent API are: • Lock: This is the base interface for Lock API. It provides all the features of synchronized keyword with additional ways to create different Conditions for locking • lock() to acquire the lock, • unlock() to release the lock • Condition: object created by Lock object • Having some important methods , await() that is similar to wait() and signal() similar to notify()

  34. CPIT 305 Advance Programming Explicit Lock • The general form of Lock constructor statement is as follows: • Lock mylock = new ReentrantLock(); • To acquire the lock use: • mylock.lock(); • To release the lock use: • mylock.unlock();

  35. CPIT 305 Advance Programming Explicit Lock • ReadWriteLock Interface: • ReentrantReadWriteLock: It contains a pair of associated locks, one for read-only operations and another one for writing. The read lock may be held simultaneously by multiple reader threads as long as there are no writer threads. The write lock is exclusive. • The general form of ReadWriteLock constructor statement is as follows: • ReadWriteLockrwl = new ReentrantReadWriteLock();

  36. CPIT 305 Advance Programming Explicit Lock • Example: • readWriteLock.readLock().lock(); // multiple readers can enter this section // if not locked for writing, and not writers waiting // to lock for writing. • readWriteLock.readLock().unlock(); • readWriteLock.writeLock().lock(); // only one writer can enter this section, // and only if no threads are currently reading. • readWriteLock.writeLock().unlock();

More Related