Skip to main content

Introduction to Java Programming

  What is Java? Java is a programming language and a platform. Java is a high-level, robust, object-oriented and secure programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Firstly, it was called  Greentalk  and the file extension was  .gt . After that, it was called  Oak . Initially Java was designed for small, embedded systems in electronic appliances like set-top boxes. Platform:  Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API(Application Programming Interface), it is called a platform. The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High performance, Multithreaded, Architecture neutral, Object-oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming, mobile devices, g...

23. Introduction to Multithreading

 

Multithreading in Java

  • Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
  • Each part of such program is called a thread. So, threads are light-weighted processes within a process.

Difference between Multithreading and Multiprocessing

  • Multithreading is the logical extension of multiprogramming.
  • In this system, the CPU executes multiple jobs by switching among them typically using a small time quantum, and these switches occur so frequently that the users can interact with each program while it is running.
  • Multiprocessing is a system that has two or more than two processors. In this, CPUs are added for increasing computing speed of the system.
  • Because of Multiprocessing, there are many processes that are executed simultaneously.

Life Cycle of a Thread

A thread in Java at any point of time exists in any of the following states. A thread lies only in one of the shown states at any instant:

  • New
  • Active
  • Blocked/Waiting
  • Timed waiting
  • Terminated

New

  • Whenever a new thread is created, it is always in the new state.
  • For a thread in the new state, the code has not been run yet and thus has not begin its execution.

Active

  • When a thread invokes the start() method, it moves from the new state to the active state.
  • The active state contains two states within it: one is runnable and the other is running.
    • Runnable: A thread, that is ready to run is then moved to the runnable state.
      • In this, the thread may be ready to run or may be running at any given instant of time.
      • It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread in the running state.
    • Running: When the thread gets the CPU, it moves from the runnable to the running state.
      • Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.

Blocked or Running

  • Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state.
  • A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread.
  • When the main thread invokes the join() method, then it is said that the main thread is in the waiting state.
  • When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.
  • If a currently running thread is moved to blocked/waiting state, another thread is in the runnable state is scheduled by the thread scheduler to run.

Timed Waiting

  • If a thread has entered the critical section of a code and is not willing to leave that critical section. Then, another thread has to wait forever.
  • To avoid such scenario, a timed waiting state is given to the other thread.
  • The sleep() method puts the thread in the times waiting state.
  • After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated

  • A thread terminates because of either of the following reasons:
    • Because it exists normally. This happens when the code of thread has entirely executed by the program.
    • Because there occurred some unusual events, like segmentation fault or an unhandled exception.
  • A thread that lies in a terminated state does no longer consumes any cycles of CPU.
class A extends Thread {
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("The state of Thread t1 while it invoked the method join() on thread t2: " + ThreadStates.t1.getState());
    }
}

public class ThreadStates extends Thread {
    public static ThreadStates t1;

    public static void main(String[] arr) {
        t1 = new ThreadStates();
        System.out.println("The state of Thread t1 after spawning it: " + t1.getState());
        t1.start();
        System.out.println("The state of Thread t1 after invoking the method start() on it: " + t1.getState());
    }

    public void run() {
        A t2 = new A();
        System.out.println("The state of Thread t2 after spawning it: " + t2.getState());
        t2.start();
        System.out.println("The state of Thread t2 after invoking the method start() on it: " + t2.getState());
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("The state of Thread t2 after invoking the method sleep() on it: " + t2.getState());
        try {
            t2.join();
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("The state of Thread t2 when it has completed it's execution: " + t2.getState());
        System.out.println("The state of Thread t1 when t2 has completed it's execution: " + t1.getState());
        System.out.println("Here we can't show the TERMINATED state of t1 inside this class,
        as t1 is the object of this class, and will terminate only when this class will terminate.");
    }
}

Output :

The state of Thread t1 after spawning it: NEW
The state of Thread t1 after invoking the method start() on it: RUNNABLE
The state of Thread t2 after spawning it: NEW
The state of Thread t2 after invoking the method start() on it: RUNNABLE
The state of Thread t2 after invoking the method sleep() on it: TIMED_WAITING
The state of Thread t1 while it invoked the method join() on thread t2: WAITING
The state of Thread t2 when it has completed it's execution: TERMINATED
The state of Thread t1 when t2 has completed it's execution: RUNNABLE
Here we can't show the TERMINATED state of t1 inside this class, as t1 is the object of this class, and will terminate only when this class will terminate.

Previous

Next

Comments