Multithreading In Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Wednesday, July 27, 2016

Multithreading In Java

Multithreading in java

Multithreading is a java feature that allow concurrent execution of two or more part of program to run. Multithreading is specialized form of multitasking.

Mutitasking

Mutitasking is a process of executing multiple task simultaneously for maximum CPU utilization.

There are two form of multitasking.

  1. Process-based multitasking.
  2. Thread-based multitasking.

Process-based multitasking is feature that allow computer to run two or more programs concurrently.

Thread-based multitasking is feature in which a single program can perform two or more tasks simultaneously.

Difference between process and thread.

Process Thread
Multitasking processes require more overhead than multitasking threads. Multitasking threads require less overhead than multitasking processes.
processes are heavyweight task that require their own separate address spaces. Threads on other hands are light weight. They share the same address space and cooperatively share the same heavyweight process.
Interprocess communication is expensive and limited. Inter-process communication is inexpensive.
Context switching from one process to another process is also costly. context switching from one thread to next is lower in cost.

Multithreading enables you to write efficient programs that make maximum use of the processing power available in the system. Multithreading achieve this by keeping ideal time low.

Thread can be created by two mechanism.

  1. Extending Thread class.
  2. Implementing Runnable interface

Thread class:

Java’s multithreading system is built upon the Thread class, its constructors, its methods, and it implements interface, Runnable.

Thread class defines several methods, some of them are listed below.

Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.

1. Create thread by extending Thread class:

To create a thread is to create a new class that extends java.lang.Thread class.The extending class must override the run() method, which is entry point of the new thread. It must call start() method to begin execution of a thread. if we call run() method directly with thread class object it will run like normal method of the class, it will not behave like thread. Every thread have their own call stack.
Create object of new class and call start() method to start the execution of a thread. start() invokes the run() method on the Thread object.

// Java code for thread creation by extending
// the Thread class
public class MyThread extends Thread {
 @Override
 public void run() {
  System.out.println("Thread " + Thread.currentThread().getName()
    + " is running");
  try {
   Thread.sleep(1000); // Thread sleep for 1 second
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  for (int i = 0; i <= 9; i++) {
   MyThread myThread = new MyThread();
   myThread.start();
  }
 }
}
Output:
Thread Thread-0 is running
Thread Thread-3 is running
Thread Thread-1 is running
Thread Thread-2 is running
Thread Thread-4 is running
Thread Thread-5 is running
Thread Thread-7 is running
Thread Thread-8 is running
Thread Thread-6 is running
Thread Thread-9 is running

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

2. Create thread by implementing Runnable interface:

We can create a new class that will implements java.lang.Runnable interface and class need only implement a single method called run(). Now we instantiate a thread object and call start() method on this object, that will internally call run() method.

// Java code for thread creation by implementing
// the Runnable interface
public class MyThread implements Runnable {
 @Override
 public void run() {
  System.out.println("Thread " + Thread.currentThread().getName()
    + " is running");
  try {
   Thread.sleep(1000); // Thread sleep for 1 second
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) {
  for (int i = 0; i <= 9; i++) {
   Thread myThread = new Thread(new MyThread());
   myThread.start();
  }
 }
}
Output:
Thread Thread-0 is running
Thread Thread-3 is running
Thread Thread-1 is running
Thread Thread-2 is running
Thread Thread-4 is running
Thread Thread-5 is running
Thread Thread-7 is running
Thread Thread-8 is running
Thread Thread-6 is running
Thread Thread-9 is running

Thread Priorities:

Thread priorities are integers that specify the relative priority of one thread to another. Thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch.

When context switching can take place:

  • A thread can voluntarily relinquish control.This is done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.
  • In cases where two threads with the same priority are competing for CPU cycles, the situation is a bit complicated. For operating systems such as Windows, threads of equal priority are time-sliced automatically in round-robin fashion. For other types of operating systems, threads of equal priority must voluntarily yield control to their peers. If they don’t, the other threads will not run.

About The Main Thread:

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. 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.

No comments :

Post a Comment