0% found this document useful (0 votes)
22 views

Threads in Java

Uploaded by

derrickcalvince
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Threads in Java

Uploaded by

derrickcalvince
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

THREADS IN JAVA

A thread in Java is the direction or path that is taken while a program is being executed. Generally, all
the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution. At this point, when the main thread is
provided, the main() method is invoked by the main thread.
A thread is critical in the program because it enables multiple operations to take place within a single
method. Each thread in the program often has its own program counter, stack, and local variable.

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. Java Multithreading is mostly used in games, animation, etc.

Why Threads in Java?

1) To maintain responsiveness of an application during a long running task.


2) To enable cancellation of separate tasks.
3) Some problems are intrinsically parallel.
4) To monitor status of some resources (Databases).
5) Some APIs and Systems demands it e,g Swing.

Application of Thread

When we execute an application: - The JVM creates a Thread object whose task is defined by the
main() method - It starts the thread - The thread executes the statements of the program one by one
until the method returns and the thread dies

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 1


Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

o Threads share the same address space.


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

N/B: At least one process is required for each thread.

What is Thread in java

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.

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 2


As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have multiple
threads. A thread is critical in the program because it enables multiple operations to take place within
a single method. Each thread in the program often has its own program counter, stack, and local
variable.

Life Cycle of Thread.

There are different states Thread transfers into during its lifetime, let us know about those states
in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 3


We can see the working of different states in a Thread in the above Diagram, let us know in detail
each and every state:
1. New State
By Default, a Thread will be a new state, in this state, code has not yet been run and the execution
process is not yet initiated.
2. Active State
A Thread that is a new state by default gets transferred to Active state when it invokes the start()
method, his Active state contains two sub-states namely :
• Runnable State: In This State, The Thread is ready to run at any given time and it’s
the job of the Thread Scheduler to provide the thread time for the runnable state
preserved threads. A program that has obtained Multithreading shares slices of time
intervals which are shared between threads hence, these threads run for some short
span of time and wait in the runnable state to get their schedules slice of a time
interval.
• Running State: When The Thread Receives CPU allocated by Thread Scheduler, it
transfers from “Runnable” state to “Running” state. and after the expiry of its given
time slice session, it again moves back to the “Runnable” state and waits for its next
time slice.
3. Waiting/Blocked State
If a Thread is inactive but on a temporary time, then either it is at waiting or blocked state, for
example, if there are two threads, T1 and T2 where T1 need to communicate to the camera and
other thread T2 already using a camera to scan then T1 waits until T2 Thread completes its work,
at this state T1 is parked in waiting for the state, and in another scenario, the user called two
Threads T2 and T3 with the same functionality and both had same time slice given by Thread
Scheduler then both Threads T1, T2 is in a blocked state. When there are multiple threads parked

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 4


in Blocked/Waiting state Thread Scheduler clears Queue by rejecting unwanted Threads and
allocating CPU on a priority basis.
4. Timed Waiting State
Sometimes the longer duration of waiting for threads causes starvation, if we take an example like
there are two threads T1, T2 waiting for CPU and T1 is undergoing Critical Coding operation and
if it does not exit CPU until its operation gets executed then T2 will be exposed to longer waiting
with undetermined certainty, In order to avoid this starvation situation, we had Timed Waiting for
the state to avoid that kind of scenario as in Timed Waiting, each thread has a time period for
which sleep() method is invoked and after the time expires the Threads starts executing its task.
5. Terminated State
A thread will be in Terminated State, due to the below reasons:
• Termination is achieved by a Thread when it finishes its task Normally.
• Sometimes Threads may be terminated due to unusual events like segmentation faults,
exceptions…etc. and such kind of Termination can be called Abnormal Termination.
• A terminated Thread means it is dead and no longer available.

Java Threads | How to create a thread in Java

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1) 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:


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

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 5


Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

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().

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 6


1. public void run(): is used to perform action for a thread.

IMPLEMENTATION

1) Using Thread Class:

class WAINAINA extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
WAINAINA student=new WAINAINA ();
student.start();
}
}

2) Using Runnable Interface - Thread (Runnable r)

class WAINAINA implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
WAINAINA student=new WAINAINA();
Thread bscit =new Thread(student);// Using the constructor Thread(Runnable student)
bscit.start();
}
}

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 7


3) Using Thread Class - Thread (String name)

public class WAINAINA extends Thread


{
public void run()
{
System.out.println("thread running...");
}
public static void main(String argvs[])
{
WAINAINA student=new WAINAINA();
// creating an object of the Thread class using the constructor Thread(String name)
Thread y2s1= new Thread("My thread");
// the start() method moves the thread to the active state
student.start();
y2s1.start();
// getting the thread name by invoking the getName() method
System.out.println("Thread Name: "+y2s1.getName());
}
}
4) Using Runnable Interface and Thread Class - Thread (Runnable r, String name)

public class WAINAINA extends Thread implements Runnable


{
public void run()
{
System.out.println("thread running...");
}
public static void main(String argvs[])
{
WAINAINA student=new WAINAINA();
// creating an object of the Thread class using the constructor Thread(String name)
Thread y2s1= new Thread(student,"My first thread");
// the start() method moves the thread to the active state
y2s1.start();
// getting the thread name by invoking the getName() method

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 8


System.out.println("Thread Name: "+y2s1.getName());
}
}

5) Sleep () method in Java on the custom thread.

class WAINAINA extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
// the thread will sleep for the 2 seconds
try
{
Thread.sleep(2000);
}
catch(InterruptedException university) // You can also use catch(Exception university)
{
System.out.println(university);
}
System.out.println("Thread="+i);
}
}
public static void main(String args[])
{
WAINAINA student=new WAINAINA();
student.start();
}
}

6) Example of the sleep() Method in Java : on the main thread

class WAINAINA extends Thread


{
// main method

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 9


public static void main(String argvs[])
{
for (int j = 0; j <= 5; j++)
{
try
{
//The main thread sleeps for the 2000 milliseconds, which is 2 sec
Thread.sleep(2000);
}
catch (Exception university)
{
// catching the exception
System.out.println(university);
}
// displaying the value of the variable
System.out.println("Thread="+j);
}
}
}
7) Sleep () method in Java on the custom thread with several threads.

class WAINAINA extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
// the thread will sleep for the 2 seconds
try
{
Thread.sleep(2000);
}
catch(InterruptedException university) // You can also use catch(Exception university)
{
System.out.println(university);
}

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 10


System.out.println("Thread="+i);
}
}
public static void main(String args[])
{
WAINAINA student=new WAINAINA();
WAINAINA y2s1=new WAINAINA();
student.start();
y2s1.start();
}
}

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 11

You might also like