Md09 multithreading


Published on

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Md09 multithreading

  1. 1. Threads and Multithreading
  2. 2. Objectives • Define a thread. • Create separate threads in a Java technology program, controlling the code and data that are used by that thread. • Control the execution of a thread and write platform­ independent code with threads. • Describe the difficulties that might arise when multiple threads share data. • Use wait and notify to communicate between threads. • Use synchronized to protect data from corruption.
  3. 3. <ul><li>Sequential program </li></ul><ul><ul><li>Sequential program ,means having beginning a </li></ul></ul><ul><ul><li>execution sequence and an end. </li></ul></ul><ul><ul><li>Thread </li></ul></ul><ul><ul><li>Thread is similar to sequential program, it has </li></ul></ul><ul><ul><li>beginning , an execution sequence and an end, thread </li></ul></ul><ul><ul><li>itself is not a program as it cannot run on its own, rather </li></ul></ul><ul><ul><li>it runs within a program. </li></ul></ul>
  4. 4. <ul><ul><li>The real advantage threading is not to have a single </li></ul></ul><ul><ul><li>sequential thread , rather its about the use of multiple </li></ul></ul><ul><ul><li>thread running at the same time and performing </li></ul></ul><ul><ul><li>different tasks in a single program. </li></ul></ul>
  5. 5. <ul><ul><li>Multithreading </li></ul></ul><ul><ul><li>The ability of an operating system to execute different </li></ul></ul><ul><ul><li>parts of a program , called threads, simultaneously . </li></ul></ul><ul><ul><li>(illusion actually there are certain scheduling algorithm that </li></ul></ul><ul><ul><li>needs to be followed) </li></ul></ul><ul><ul><li>The programmer must carefully design the program in such a </li></ul></ul><ul><ul><li>way that all the threads can run at the same time without </li></ul></ul><ul><ul><li>interfering with each other. </li></ul></ul>
  6. 6. Example :- Web browser Scroll a page while its downloading an applet Play animation and sound concurrently Print a page in the background
  7. 7. Multitasking The ability to execute more than one task at the same time. The terms multitasking and multiprocessing are often used interchangeably. Although multiprocessing implies that more than one CPU is involved. In multitasking, only one CPU is involved, but it switches from one program to another so quickly that it gives the appearance of executing all of the programs at the same time.
  8. 8. <ul><ul><li>Two distinct types of multitasking : </li></ul></ul><ul><ul><li>Process-based </li></ul></ul><ul><ul><li>Thread-based. </li></ul></ul>
  9. 9. <ul><li>Process-based multitasking </li></ul><ul><ul><li>is the feature that allows your computer to run </li></ul></ul><ul><ul><li>two or more programs concurrently. </li></ul></ul><ul><ul><li>For example , process-based multitasking enables you to </li></ul></ul><ul><ul><li>run the Java compiler at the same time that you are </li></ul></ul><ul><ul><li>using a text editor. </li></ul></ul>
  10. 10. <ul><li>Thread-based multitasking </li></ul><ul><ul><li>The thread is the smallest unit of dispatchable code. </li></ul></ul><ul><ul><li>A single program can perform two or more tasks </li></ul></ul><ul><ul><li>simultaneously. </li></ul></ul><ul><ul><li>For example , a text editor can format text at the same time </li></ul></ul><ul><ul><li>that it is printing, as long as these two actions are being </li></ul></ul><ul><ul><li>performed by two separate threads. </li></ul></ul>
  11. 11. <ul><li>Thread Priorities </li></ul><ul><ul><li>Every thread has a priority , Thread with higher </li></ul></ul><ul><ul><li>priority are executed in preference to threads with </li></ul></ul><ul><ul><li>lower priority,when code running in some thread </li></ul></ul><ul><ul><li>creates a new Thread object , the new thread has its </li></ul></ul><ul><ul><li>priority initially set equal to the priority of creating </li></ul></ul><ul><ul><li>thread. </li></ul></ul><ul><li>Setting the priority of a thread </li></ul><ul><li>FooRunnable r = new FooRunnable(); </li></ul><ul><li>Thread t = new Thread(r); </li></ul><ul><li>t.setPriority(8); </li></ul><ul><li>t.start(); </li></ul>
  12. 12. <ul><li>Remember </li></ul><ul><ul><li>Thread.MIN_PRIORITY (1) </li></ul></ul><ul><ul><li>Thread.NORM_PRIORITY (5) </li></ul></ul><ul><ul><li>Thread.MAX_PRIORITY (10) </li></ul></ul>
  13. 13. <ul><li>Two ways to create new thread of execution </li></ul><ul><ul><li>1.Declare a class to be subclass of Thread, this subclass </li></ul></ul><ul><ul><li>should override the run method of class Thread. </li></ul></ul><ul><ul><li>Example ( ) </li></ul></ul><ul><ul><ul><li>class PrimeThread extends Thread { </li></ul></ul></ul><ul><ul><ul><li>long minPrime; </li></ul></ul></ul><ul><ul><ul><li>PrimeThread(long minPrime) { </li></ul></ul></ul><ul><ul><ul><li>this.minPrime = minPrime; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>public void run() { </li></ul></ul></ul><ul><ul><ul><li>// compute primes larger than minPrime </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  14. 14. 2.Declare a class that implements the Runnable interface, that class then implements the run method   Example ( class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime   } }
  15. 15. <ul><ul><li>In both cases then create a thread and start it running: </li></ul></ul><ul><ul><li>PrimeThread p = new PrimeThread(143); </li></ul></ul><ul><ul><li>p.start(); </li></ul></ul><ul><ul><li>If a class must subclass some other class use </li></ul></ul><ul><ul><li>Runnable as in case of applets ,since a class </li></ul></ul><ul><ul><li>cannot be a subclass of both Thread and Applet , </li></ul></ul><ul><ul><li>Thus the class use the Runnable interface. </li></ul></ul>
  16. 16. <ul><li>The Main Thread </li></ul><ul><li>When a Java program starts up, one thread begins </li></ul><ul><li>running immediately. This is usually called the main thread </li></ul><ul><li>of your program. </li></ul><ul><ul><li>The main thread is important for two reasons: </li></ul></ul><ul><ul><li>■ It is the thread from which other “child” threads </li></ul></ul><ul><ul><li>will be spawned. </li></ul></ul><ul><ul><li>■ Often it must be the last thread to finish execution </li></ul></ul><ul><ul><li>because it performs various shutdown actions. </li></ul></ul>
  17. 17. Life cycle of Thread
  18. 18. <ul><ul><li>New Thread </li></ul></ul><ul><ul><li>Thread clockThread= new Thread(this, “Clock”); </li></ul></ul><ul><ul><li>//new Thread(Runnable Target, String name) </li></ul></ul><ul><ul><li>After this statement is executed clockThread is in New </li></ul></ul><ul><ul><li>Thread state. </li></ul></ul><ul><ul><li>Thread in this state is merely an empty Thread object , </li></ul></ul><ul><ul><li>no system resources have been allocated for it yet. </li></ul></ul><ul><ul><li>At this stage the thread is not considered to be alive. </li></ul></ul><ul><ul><li>When the thread is in this state we can only start the thread. </li></ul></ul><ul><ul><li>Calling any other method besides start , cause </li></ul></ul><ul><ul><li>IllegalThreadStateException. </li></ul></ul>
  19. 19. <ul><ul><li>Runnable </li></ul></ul><ul><ul><li>clockThread.start(); </li></ul></ul><ul><ul><li>This is the state a thread is in when it's eligible to run, but the </li></ul></ul><ul><ul><li>scheduler has not selected it to be the running thread. </li></ul></ul><ul><ul><li>A thread first enters the runnable state when the start() </li></ul></ul><ul><ul><li>method is invoked, but a thread can also return to the runnable </li></ul></ul><ul><ul><li>state after either running or coming back from a blocked, waiting, </li></ul></ul><ul><ul><li>or sleeping state. </li></ul></ul><ul><ul><li>When the thread is in the runnable state,it is considered alive . </li></ul></ul>
  20. 20. Running This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread can transition out of a running state for several reasons,
  21. 21. <ul><ul><li>Not Runnable </li></ul></ul><ul><ul><li>To make a thread not runnable </li></ul></ul><ul><ul><ul><ul><li>* Its sleep method is invoked </li></ul></ul></ul></ul><ul><ul><ul><ul><li>* The thread call the wait method to wait for specific </li></ul></ul></ul></ul><ul><ul><ul><ul><li>condition to be satisfied </li></ul></ul></ul></ul><ul><ul><ul><ul><li>* The thread is blocking on IO </li></ul></ul></ul></ul>
  22. 22. <ul><ul><li>Not Runnable to Runnable </li></ul></ul><ul><ul><li>Exit for every entrance to Not Runnable state </li></ul></ul><ul><ul><li>If the thread is put to sleep , the specified number of </li></ul></ul><ul><ul><li>milliseconds must elapse. </li></ul></ul><ul><ul><li>If the thread is waiting for a condition,then another </li></ul></ul><ul><ul><li>object must notify the waiting thread of a change in </li></ul></ul><ul><ul><li>condition by calling notify or notifyAll. </li></ul></ul><ul><ul><li>If the thread is blocked on I/O, the I/O must complete. </li></ul></ul><ul><ul><li>Stop </li></ul></ul><ul><ul><li>Thread stops when the run method terminates. </li></ul></ul>
  23. 23. <ul><ul><li>Testing Thread States </li></ul></ul><ul><ul><li>Thread.getState() method return one of the thread </li></ul></ul><ul><ul><li>states </li></ul></ul><ul><ul><li>NEW RUNNABLE BLOCKED WAITING </li></ul></ul><ul><ul><li>TERMINATED </li></ul></ul><ul><li>isAlive() method returns true if thread has been </li></ul><ul><li>started and not stopped </li></ul><ul><li>(when it is either Runnable or Not Runnable) </li></ul><ul><li>isAlive() returns false if thread is a New Thread or </li></ul><ul><li>is Dead </li></ul>
  24. 24. <ul><li>How to cause the thread to execute from a class that implements </li></ul><ul><li>Runnable? </li></ul><ul><ul><ul><ul><ul><li>class MyClass implements Runnable { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li> public void run() { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>for(int x =1; x < 6; x++) { </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>System.out.println(&quot;Runnable running&quot;); </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>} </li></ul></ul></ul></ul></ul><ul><ul><li>Is this right to cause the thread to execute? </li></ul></ul><ul><ul><ul><li>Runnable r = new Runnable(); </li></ul></ul></ul><ul><ul><ul><li>; </li></ul></ul></ul>
  25. 25. <ul><ul><li>Remember, every thread of execution begins as an instance of </li></ul></ul><ul><ul><li>class Thread.Regardless of whether your run() method is in a </li></ul></ul><ul><ul><li>Thread subclass or a Runnable implementation class, you still need </li></ul></ul><ul><ul><li>a Thread object to do the work. </li></ul></ul><ul><ul><li>MyClass mc = new MyClass(); Thread t = new Thread(mc); t.start(); </li></ul></ul><ul><li>Although it is the run method code that executes, a thread is actually </li></ul><ul><li>started via the start method </li></ul>
  26. 26. <ul><ul><li>Thread Scheduling  </li></ul></ul><ul><ul><li>Execution of multiple threads on a single CPU in </li></ul></ul><ul><ul><li>some order is called scheduling. </li></ul></ul><ul><ul><li>JRE support a very simple scheduling algorithms </li></ul></ul><ul><ul><li>called </li></ul></ul><ul><ul><li>Fixed priority scheduling. </li></ul></ul><ul><ul><li>Time Slicing scheduling. </li></ul></ul><ul><ul><li>When a thread is created, it inherit its property from </li></ul></ul><ul><ul><li>the thread that created it ,modify the thread priority </li></ul></ul><ul><ul><li>at any time by using setPriority method. </li></ul></ul>
  27. 27. <ul><ul><li>Relinquishing the CPU </li></ul></ul><ul><ul><li>A thread can voluntarily yield the CPU by calling the </li></ul></ul><ul><ul><li>yield method. The yield method gives other threads of the </li></ul></ul><ul><ul><li>same priority a chance to run. If no equal-priority threads </li></ul></ul><ul><ul><li>are Runnable, the yield is ignored. </li></ul></ul>
  28. 28. <ul><li>Is it possible to overload the run() method in your Thread subclass? </li></ul><ul><li>class MyThread extends Thread { </li></ul><ul><ul><li>public void run() { </li></ul></ul><ul><ul><li>System.out.println(&quot;Important job running in MyThread&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>public void run(String s) { </li></ul></ul><ul><ul><li>System.out.println(&quot;String in run is &quot; + s); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>} </li></ul>
  29. 29. The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.
  30. 31. <ul><ul><li>Synchronizing Threads </li></ul></ul><ul><ul><li>Imagine an application in which one thread write </li></ul></ul><ul><ul><li>data to a file while second thread read data from the </li></ul></ul><ul><ul><li>same file, as the thread share a common resource (file) </li></ul></ul><ul><ul><li>they must be synchronized. </li></ul></ul><ul><ul><li>Example </li></ul></ul><ul><ul><li> </li></ul></ul><ul><ul><li>Producer generates an integer between 0 and 9, </li></ul></ul><ul><ul><li>store it in CubbyHole object </li></ul></ul><ul><ul><li>Consumer consumes all integer from the CubbyHole </li></ul></ul><ul><ul><li>as quickly as they become available </li></ul></ul>
  31. 32. <ul><ul><li>Race Condition </li></ul></ul><ul><ul><li>One problem arises when the Producer is quicker than </li></ul></ul><ul><ul><li>the Consumer and generates two numbers before the </li></ul></ul><ul><ul><li>Consumer has a chance to consume the first one </li></ul></ul>Another problem might arise when the Consumer is quicker than the Producer and consumes the same value twice. In this situation, the Consumer might produce output that looks like this:
  32. 33. A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled,
  33. 34. <ul><ul><li>Race condition can be prevented by </li></ul></ul><ul><ul><li>1.Synchronizing the storage and retrieval of integer. </li></ul></ul><ul><ul><li>2. Second, the two threads must do some simple </li></ul></ul><ul><ul><li>coordination. That is, the Producer must have a way to </li></ul></ul><ul><ul><li>indicate to the Consumer that the value is ready, and </li></ul></ul><ul><ul><li>the Consumer must have a way to indicate that the </li></ul></ul><ul><ul><li>value has been retrieved. The Object class provides </li></ul></ul><ul><ul><li>a collection of methods — wait , notify , and notify All </li></ul></ul><ul><ul><li>Note You can easily wake up wait with a notify but a </li></ul></ul><ul><ul><li>sleeping thread cannot be awakened prematurely before </li></ul></ul><ul><ul><li>the specified time elapse. </li></ul></ul>
  34. 35. <ul><ul><li>Starvation & Deadlock </li></ul></ul><ul><ul><li>Starvation occurs when one or more threads in your </li></ul></ul><ul><ul><li>program are blocked from gaining access to a resource, </li></ul></ul><ul><ul><li>and deadlock in one of the ultimate form of starvation </li></ul></ul><ul><ul><li>when two or more threads are waiting for the other to </li></ul></ul><ul><ul><li>do something. </li></ul></ul><ul><ul><li>Example DeadLockExample </li></ul></ul>
  35. 36. <ul><ul><li>Other Examples </li></ul></ul><ul><ul><li>Using isAlive( ) and join( ) </li></ul></ul><ul><ul><li>Thread Priority </li></ul></ul>