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

Md09 multithreading

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