You are on page 1of 21

Object Oriented Programming using

JAVA (Professional Elective-1)


Course Code: CS1529
Course Instructor: Dr. Ashish Kumar Sahu

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 1


Multithreading
Introduction
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less
time than process.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 3


Advantages of Java Multithreading

 It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 4


Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU.
 Multitasking can be achieved in two ways:

1. Process-based Multitasking (Multiprocessing)


2. Thread-based Multitasking (Multithreading)

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 5


Process-based Multitasking (Multiprocessing)

 Each process has an address in memory. In other words, each process


allocates a separate memory area.
 A process is heavy weight.
 Cost of communication between the process is high.
 Switching from one process to another requires some time for saving
and loading registers, memory maps, updating lists, etc.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 6


Thread-based Multitasking (Multithreading)

 Threads share the same address space.


 A thread is lightweight.
 Cost of communication between the thread is low.

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 7


Department of Computer Science and Engineering National Institute of Technology Jamshedpur 8
Java Thread class
Java provides Thread class to achieve thread programming.
Thread class provides constructors and methods to create and perform operations on a thread.

Modifier and Type Method Description


void start() It is used to start the execution of the thread.
void run() It is used to do an action for a thread.
static void sleep() It sleeps a thread for the specified amount of time.

static Thread currentThread() It returns a reference to the currently executing thread object.

void join() It waits for a thread to die.


int getPriority() It returns the priority of the thread.
void setPriority() It changes the priority of the thread.
String getName() It returns the name of the thread.
void setName() It changes the name of the thread.
long getId() It returns the id of the thread.
Department of Computer Science and Engineering National Institute of Technology Jamshedpur 9
boolean isAlive() It tests if the thread is alive.
static void yield() It causes the currently executing thread object to pause and allow other threads to execute temporarily.

void suspend() It is used to suspend the thread.


void resume() It is used to resume the suspended thread.
void stop() It is used to stop the thread.
void destroy() It is used to destroy the thread group and all of its subgroups.

boolean isDaemon() It tests if the thread is a daemon thread.


void setDaemon() It marks the thread as daemon or user thread.
void interrupt() It interrupts the thread.
boolean isinterrupted() It tests whether the thread has been interrupted.

static boolean interrupted() It tests whether the current thread has been interrupted.

static int activeCount() It returns the number of active threads in the current thread's thread group.

void checkAccess() It determines if the currently running thread has permission to modify the thread.

static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object.

static void dumpStack() It is used to print a stack trace of the current thread to the standard error stream.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 10


Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These
states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 11


1. 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 begun its execution.
2. 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.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 12


1. Runnable: A thread, that is ready to run is then moved to the runnable state.
In the runnable state, the thread may be running or may be ready to run 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 the running state.
2. 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.
3. Blocked or Waiting: 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.
Department of Computer Science and Engineering National Institute of Technology Jamshedpur 13
4. Timed Waiting: A thread is in TIMED_WAITING state when it's
waiting for another thread to perform a particular action within a
stipulated amount of time.
5. Terminated: A thread reaches the termination state because of the
following reasons:
1. When a thread has finished its job, then it exists or terminates normally.
2. Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 14


Department of Computer Science and Engineering National Institute of Technology Jamshedpur 15
Implementation of Thread States

The java.lang.Thread.State class of Java provides the constants


ENUM to represent the state of a thread. These constants are:
public static final Thread.State state_name

state_name {NEW, RUNNABLE, BLOCKED , WAITING,


TIMED_WAITING , TERMINATED}

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 16


Java Threads

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 17


1. Thread class

Thread class provide constructors and methods to create and perform


operations on a thread.

Commonly used Constructors of Thread class:


• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 18


 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
 public void sleep(long milliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified milliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing thread.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 19


 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 20


2. Runnable interface:

The Runnable interface should be implemented by any class whose


instances are intended to be executed by a thread. Runnable interface
have only one method named run().
 public void run(): is used to perform action for a thread.

Department of Computer Science and Engineering National Institute of Technology Jamshedpur 21

You might also like