0% found this document useful (0 votes)
1 views10 pages

Multithreading in Java

The document provides an overview of multithreading in Java, explaining the concept of threads as lightweight sub-processes that allow concurrent execution within a program. It details the creation of threads through inheritance of the Thread class or by implementing the Runnable interface, as well as the various states a thread can be in during its lifecycle, including New, Runnable, Not Runnable, Waiting, Timed Waiting, Blocked, and Terminated. Additionally, it highlights the role of the main thread and the methods available for managing thread execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views10 pages

Multithreading in Java

The document provides an overview of multithreading in Java, explaining the concept of threads as lightweight sub-processes that allow concurrent execution within a program. It details the creation of threads through inheritance of the Thread class or by implementing the Runnable interface, as well as the various states a thread can be in during its lifecycle, including New, Runnable, Not Runnable, Waiting, Timed Waiting, Blocked, and Terminated. Additionally, it highlights the role of the main thread and the methods available for managing thread execution.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Multithreading in Java

Introduction

 Multithreading is a process of executing multiple threads


simultaneously.
 A thread is a lightweight sub-process, the smallest unit of processing.
(each performing different tasks, within a single program)
 Multitasking can either be
o process-based
o thread-based.

 Process-based:
o Execution of more than one program concurrently.
o Processes are heavyweight.
o Each process has separate memory area.
o Switching of CPU from one process to another requires more
overhead as each process has separate memory area.

 Thread-based:
o Executing a single program having more than one thread,
performing different tasks simultaneously.
o Threads are lightweight.
o Threads share the same address space.
o Switching of CPU occurs within the program within same address
space; require less overhead.

 The objective of multitasking is


o maximum utilization of CPU and
o minimizing idle time of CPU.
Multithreading in Java

 Every Java program has at least one thread, i.e., the main thread.
Whenever a program starts executing, the JVM is responsible for
creating the main thread and calling the main() method, from within that
thread.
 A thread can either die naturally or be forced to die.
o A thread dies naturally when it exits the run() method normally.
o A thread can be killed by calling interrupt() method.

java.lang.Thread

 There is a class named as Thread class, which belongs to the java.lang


package, which is the core class for working with threads.
 It provides methods to create, manage, and control threads in a
program.
 Threads are created as the instance of this class, which contains run()
methods in it. functionality of the thread can only be achieved by
overriding this run() method.

structure of run():

public void run()


{
......
// statement for implementing thread
......
}

This method is automatically invoked when a thread object is created and


initiated using the start() method. Some of the methods belonging to the
Thread class are listed below.
 The constructors responsible for creating threads are
1. Thread()
2. Thread(String threadName)
3. Thread(ThreadGroup threadGroup, String threadName)

Main Thread

 Even if a thread is not created by a programmer, every Java program has


a thread, the main thread.
 Whenever a program starts executing, the JVM creates the main thread
and call the main() method from within that thread.
 Apart from this, JVM also creates some invisible threads, such as threads
for garbage collection and threads responsible for object finalization.
 main thread generates other threads, which are known as child threads.
 Main thread can be controlled using a static method, currentThread()
which is used to return a reference to the current thread. The main
thread can be controlled by this reference only.

 name of the main thread can be changed from main to any new name.
Example:
package Thread_Package;
public class Demo_1 {
public static void main (String args[] ){

Thread threadObj = Thread.currentThread();


System.out.println("Current thread: " +threadObj);

threadObj.setName("New Thread");
System.out.println("Renamed Thread: "
+threadObj);
}}

CREATION OF NEW THREADS

 Two ways to create a new thread:


1. Inheriting Thread class
2. Implementing Runnable interface

 By Inheriting the Thread Class:

 Threads can be created by inheriting the java.lang.Thread class.

 Steps to be followed for thread creation:


1. Declare your own class as extending the Thread class.
2. Override the run() method, which constitutes the body of the
thread.
3. Create the thread object and use the start() method to initiate the
thread execution.

Let us elaborate these steps in detail.


1. Declaring a Class: Any new class can be created and extend the Thread
class, thus inheriting the functionalities of the Thread class.
ClassNewThread extends Thread
{
......
......
}

2. Overriding the run() Method: The run() method has to be overridden. The
thread behaves as per this code.
public void run( )
{
//code segment providing the functionality of thread
}

3. Starting New Thread: The start() method of the Thread class is used to
initiate the execution of a thread.
newThread thread1 = new newThread();
thread1.start();

 Implementing the Runnable Interface:

 The Runnable interface is an interface with only one method, which is


run().

 Steps to be followed for thread creation: (Multiple inheritance)


1. Declare a Class that Implements the Runnable Interface.
2. Override the run() Method
3. Create a Thread Object by Passing a Runnable Instance
4. Start the Thread Using the start() Method

Let us elaborate these steps in detail.


1. Declaring a Class:Create a class and implement the Runnable interface.
class MyRunnable implements Runnable
{
......
......
}

2. Overriding the run() Method: The run() method has to be overridden. This
method defines what thread will execute.

class MyRunnable implements Runnable


{
public void run( )
{
//code segment providing the functionality of thread
}
}

3. Create a Thread Object by Passing a Runnable Instance: Create an object


of the Runnable implementation class. Pass this object as an argument to
the Thread constructor.

 Constructors belonging to the Thread class are mentioned below.


o Thread(Runnable threadObj)
o Thread(Runnable threadObj, String threadName)
o Thread(ThreadGroupthreadGroup, Runnable threadObj)
o Thread(ThreadGroupthreadGroup, Runnable threadObj, String
threadName)
 In above,
o threadObj is a reference to an instance of a class that implements
the Runnable interface.
o threadName is the name of the thread. In case no name is passed
externally to the constructors, the JVM is automatically going to
name it.
o threadGroup is the group name to which the thread belongs. If no
thread group is externally specified, the group is determined by
the security managing component.

MyRunnablemyRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

4. Start the Thread Using the start() Method: Call the start() method on the
Thread object to initiate the execution of a thread.

thread.start();

Thread.State IN JAVA

 The Thread.State in Java represents the different states of a thread


during its lifecycle.
 These states are defined in the java.lang.Thread class.
 In Java, a thread can exist in one of the states mentioned below.
1. New:
2. Runnable:
3. Not Runnable:
4. Waiting:
5. Timed_Waiting:
6. Blocked:
7. Terminated:
 Below Figure shows the various states in which a Java thread exists
during its life.

 These states represent the lifecycle of a thread, from creation to


termination.

 New:

 A thread is in the NEW state when it is created but not yet started.
Thread threadObj = new ThreadDemo();

 When thread is in ‘New’ state, no system resource is allotted.


 Only start()(Runnable state) and interrupt()(Terminated state)can be
called from this state; otherwise, an IllegalThreadStateException will be
thrown.

 Runnable:

 When the start() method is called on the new instance of a thread, it


enters into a runnable state.
 Following code represents moving thread from ‘New’ state to ‘Runnable’.
threadObj.start();
 A thread is in the RUNNABLE state when it is ready for execution but is
waiting(in queue) for availability of the processor(CPU) to execute.
 Once a thread is actually being executed by the processor then it is
termed as “Running”.
 Runnable threads are those which are not actually running, but are
scheduled in queue to get the processor.

 Not Runnable:

 From runnable state, a thread might move to the not runnable state, as
shown in the Figure.
 A thread which is in any of these three states can be assumed to be in
‘not runnable’ state. These three states -WAITING,
TIMED_WAITING,BLOCKED.

 Waiting:
 The thread will be in waiting state when it calls wait() method or join()
method.
 A thread is in the WAITING state when it is waiting indefinitely for
another thread to perform a specific action (e.g., calling notify() or
notifyAll()).
 The thread remains in this state until explicitly notified.

 Timed_Waiting:

 A thread is in the TIMED_WAITING state when it is waiting for another


thread to perform an action(notify) up to a specified amount of time.
 A thread can get into this state by calling either of these methods:
sleep(),wait(), and join().

 Blocked:
 The thread will be in blocked state when it is trying to acquire a lock on
the resource but currently the lock is acquired by the other thread.
 The thread will move from the blocked state to runnable state when it
acquires the lock.

 Terminated:
 A Thread is in the terminated state when it has finished its execution.
 In this state, the thread is dead. The death of a thread can either be
natural or forceful.
o A thread dies naturally when it exits run() normally. The normal
exit from run() means the instructions of the run() has been
processed completely.
o A thread can be forcefully killed by using interrupt().

You might also like