Runnable-Extend: Creating thread
  • Multitasking :: Concurrency
    • Process: A process has a self-contained execution environment. It Contains one or many sub-processes or Threads.
    • Threads :A thread is a lightweight sub-process (at least one in each process) , the smallest unit of processing. Unlike a process a thread shares memory and data with the rest of the program. In another word, Threads share the process's resources, including memory and open files.
      • Each thread is associated with an instance of the class Thread, facilitating an asynchronous task
    • Multi-threading: A multi-threaded program contains two or more processes that can run concurrently, in parallel with other processes, and thereby handling different tasks at the using available resources, specially when your computer has multiple CPUs.
  • Defining and starting thread: Thereare two ways of creating threads.
    • Runnable object :
      implements Runnable then start() to fire-up.
      public class ex1 implements Runnable {
      
          public void run() {
              System.out.println("Hello from a thread!");
          }
      
          public static void main(String args[]) {
              (new Thread(new ex1())).start();
          }
      
      }
    • Subclass Thread: The second way to create a thread is to create a new class that extends Thread class

      public class ex1 extends Thread {

          public void run() {
              System.out.println("Hello from a thread!");
          }

          public static void main(String args[]) {
              (new ex1()).start();
          }

      }
  • Runnable vs extending Thread:
    • Extending Thread: The limitation with "extends Thread" approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.
    • Implementing Runnable: Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.
    • Loosely-Coupled:
      • "implements Runnable" makes the code loosely-coupled and easier to read .
        Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
      • "extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.
    • Function overhead: When you extend Thread, you have to inherit all the functions which may not be needing; therefore easy bypass is implementing Runnable