[Go to site: main page, start]

0% found this document useful (0 votes)
2 views34 pages

Java Thread

Uploaded by

2403012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Java Thread

Uploaded by

2403012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Multithreading in Java

Multithreading in Java is a process of executing multiple threads simultaneously.


Thread
• 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.
• Java Multithreading is mostly used in games, animation, etc.
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.
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.
We use multitasking to utilize the CPU. Multitasking can be achieved
in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process
allocates a separate memory area.
• A process is heavyweight.
• 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.
• Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
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. Thread class extends Object class and
implements Runnable interface.
Java Thread Methods
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.
boolean isAlive() It tests if the thread is alive.
void stop() It is used to stop the thread.
void interrupt() It interrupts the thread.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. The life cycle of the thread in
java is controlled by JVM. The java thread states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
Creating Thread
There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r, String name)
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().
Thread Scheduler in Java
• Thread scheduler in java is the part of the JVM that decides which
thread should run.
• There is no guarantee that which runnable thread will be chosen to
run by the thread scheduler.
• Only one thread at a time can run in a single process.
• The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
Assignment-3
Difference between preemptive scheduling
and time slicing.
Java Thread start() method
• The start() method of thread class is used to begin the execution of thread.
The result of this method is two threads that are running concurrently: the
current thread (which returns from the call to the start method) and the
other thread (which executes its run method).
• The start() method internally calls the run() method of Runnable interface
to execute the code specified in the run() method in a separate thread.
• The start thread performs the following tasks:
• It stats a new thread
• The thread moves from New State to Runnable state.
• When the thread gets a chance to execute, its target run() method will run.
Example (Extending thread class)
Implementing Runnable Interface
Sleep method in java
• The sleep() method of Thread class is used to sleep a thread for the
specified amount of time.
Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws
InterruptedException
Example

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time, the thread
shedular picks up another thread and so on.
Java Thread getPriority() method
• The getPriority() method of thread class is used to check the priority
of the thread. When we create a thread, it has some priority assigned
to it. Priority of thread can either be assigned by the JVM or by the
programmer explicitly while creating the thread.
• The thread's priority is in the range of 1 to 10. The default priority of a
thread is 5.
Syntax
public final int getPriority()
Example
Java Thread setPriority() method
The setPriority() method of thread class is used to change the thread's
priority. Every thread has a priority which is represented by the integer
number between 1 to 10.
Thread class provides 3 constant properties:
• public static int MIN_PRIORITY: It is the maximum priority of a
thread. The value of it is 1.
• public static int NORM_PRIORITY: It is the normal priority of a
thread. The value of it is 5.
• public static int MAX_PRIORITY: It is the minimum priority of a
thread. The value of it is 10.
We can also set the priority of thread between 1 to 10. This priority is
known as custom priority or user defined priority.
Syntax
public final void setPriority(int a)
Exception
• IllegalArgumentException: This exception throws if the priority is not
in the range MIN_PRIORITY to MAX_PRIORITY.
• SecurityException: This exception throws if the current thread cannot
modify this thread.
Maximum Priority Thread
Minimum Priority Thread
Normal Priority Thread
User define Priority Thread
Java Thread join() method
The join() method of thread class waits for a thread to die. It is used
when you want one thread to wait for completion of another. This
process is like a relay race where the second runner waits until the first
runner comes and hand over the flag to him.
Example
Example 2
Java Thread isAlive() method
The isAlive() method of thread class tests if the thread is alive. A thread
is considered alive when the start() method of thread class has been
called and the thread is not yet dead. This method returns true if the
thread is still running and not finished.
Example
Java Thread suspend() method
The suspend() method of thread class puts the thread from running to
waiting state. This method is used if you want to stop the thread
execution and start it again when a certain event occurs. This method
allows a thread to temporarily cease execution. The suspended thread
can be resumed using the resume() method.
Example

You might also like