Java Thread

aimtocode.COM

Thread

Thread is a single sequential flow of control. A thread is a sequence of execution within a program. The Thread class defines several methods. The following table lists the various thread methods.

  • Start: Starts a thread by calling its run method.
  • Run Defines while the thread is running.
  • Sleep Suspends thread to terminate.
  • Join Waits for thread to terminate.
  • isAlive Determines if a thread is still running.
  • getName Returns the name of the thread.
  • getPriority Returns the priority of the thread.
  • Yield Current thread to yield control of the process to the threads.


Life Cycle of a Thread:

aimtocode.COM

Example 1:



Output :

 aimtocode.com
 prayag-verma

Example 2:



Output :

 My thread is in running state
 Thread-Sleep Demo Complete


Example 3:



Output :

 My thread is in running state
 Thread-Join Demo Complete

Example 4:



Output :

 Thread[main,5,main]
 Thread State of MyThread1 before calling start: NEW
 Run by MyThread2
 Thread State of MyThread1 in Main method before Sleep: RUNNABLE
 Run by Thread-1
 Thread State of MyThread2 in Main method before Sleep: RUNNABLE
 Thread State of: MyThread2 - RUNNABLE
 Exit of Thread: MyThread2
 Thread State of: Thread-1 - RUNNABLE
 Exit of Thread: Thread-1
 Thread State of MyThread1 in Main method after Sleep: TERMINATED
 Thread State of MyThread2 in Main method after Sleep: TERMINATED
aimtocode.COM

Multithreading

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more part that can run concurrently. Each part of such a program is called a threaded a and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. this is especially important for the interactive, networked environment in which Java operates, because idle time is common.


A program can be divided into a number of small process. Each small process can be addressed as a single thread(a lightweight process). Multithreaded programs contain two or more threads that can run concurrently.

This means that a single program can perform two or more tasks simultaneously.For example, one thread is writing content on a file at the same time another thread is performing spelling check.

Advantages of Multithreading

  • Reduces the computation time.
  • Improves performance of an application.
  • Threads distribute the same address space so it saves the memory.
  • Context switching between threads is usually less costly than between processes.
  • Cost of communication between threads is comparatively low.


aimtocode.COM