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

Thread in Java (1)

Uploaded by

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

Thread in Java (1)

Uploaded by

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

Thread in Java

Threads allows a program to operate more efficiently by doing multiple things at


the same time.

Threads can be used to perform complicated tasks in the background without


interrupting the main program.

Typically, we can define threads as a subprocess with lightweight with the


smallest unit of processes and also has separate paths of execution. The main
advantage of multiple threads is efficiency (allowing multiple things at the
same time). For example, in MS Word. one thread automatically formats the
document while another thread is taking user input. Another advantage is
quick response, if we use multiple threads in a process and if a thread gets
stuck due to lack of resources or an exception, the other threads can continue
to execution, allowing the process (which represents an application) to
continue to be responsive.

Threads in a Shared Memory Environment in OS

As we can observe in, the above diagram a thread runs inside the process and
there will be context-based switching between threads there can be multiple
processes running in OS, and each process again can have multiple threads
running simultaneously. The Multithreading concept is popularly applied in
games, animation…etc.

Why thread is called light weight process


A thread is often referred to as a lightweight process for several key reasons:

1. Resource Sharing: Threads within the same process share the same
memory space and resources, such as code, data segments, and open files.
This contrasts with processes, which have separate memory spaces. This
shared environment allows for more efficient communication and resource
utilization.
2. Lower Overhead: Creating and managing threads incurs less overhead
compared to processes. Threads require less memory and fewer resources
to manage their execution context (like stack space, registers, etc.) because
they share many of these elements with other threads in the same process.
3. Faster Context Switching: Switching between threads (context switching) is
generally faster than switching between processes. This is because
switching threads does not require the operating system to change the
memory address space, whereas switching processes does.
4. Concurrency: Threads allow for concurrent execution within a single
application, making it easier to perform multiple tasks simultaneously
without the complexity of managing multiple separate processes.

5. Simplified Communication: Since threads within the same process share


memory, they can communicate more easily and efficiently than separate
processes, which typically require inter-process communication (IPC)
mechanisms such as pipes, message queues, or shared memory.

The Concept Of Multitasking

To help users Operating System accommodates users the privilege of


multitasking, where users can perform multiple actions simultaneously on the
machine. This Multitasking can be enabled in two ways:

1. Process-Based Multitasking

2. Thread-Based Multitasking
1. Process-Based Multitasking (Multiprocessing)

In this type of Multitasking, processes are heavyweight and each process was
allocated by a separate memory area. And as the process is heavyweight the
cost of communication between processes is high and it takes a long time for
switching between processes as it involves actions such as loading, saving in
registers, updating maps, lists, etc.

2. Thread-Based Multitasking

As we discussed above Threads are provided with lightweight nature and


share the same address space, and the cost of communication between
threads is also low.

Why Threads are used?

Now, we can understand why threads are being used as they had the
advantage of being lightweight and can provide communication between
multiple threads at a Low Cost contributing to effective multi-tasking within a
shared memory environment.

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
1. New State

By default, a Thread will be in 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 the “Runnable” state to the

“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 a waiting or


blocked state, for example, if there are two threads, T1 and T2 where T1 needs
to communicate to the camera and the 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 in a 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 a Critical Coding operation and if it does not exist the 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.

What is Main Thread?

As we are familiar, we create Main Method in each and every Java Program,
which acts as an entry point for the code to get executed by JVM, Similarly in
this Multithreading Concept, Each Program has one Main Thread which was
provided by default by JVM, hence whenever a program is being created in
java, JVM provides the Main Thread for its Execution.

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

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 milliseconds): 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 milliseconds): waits for a thread to die for the specified milliseconds.
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(deprecated).
16. public void resume(): is used to resume the suspended thread(deprecated).
17. public void stop(): is used to stop the thread(deprecated).
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.

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

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


Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:

○ A new thread starts(with new callstack).


○ The thread moves from New state to the Runnable state.
○ When the thread gets a chance to execute, its target run() method will
run.

1) Java Thread Example by extending Thread class


FileName: Multi.java

class Multi extends Thread{


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

thread is running...
Sample code to create Threads by Extending Thread Class:
import java.io.*;
import java.util.*;

public class GFG extends Thread {


// initiated run method for Thread
public void run()
{
System.out.println("Thread Started Running...");
}
public static void main(String[] args)
{
GFG g1 = new GFG();

// Invoking Thread using start() method


g1.start();
}
}
Output
Thread Started Running...

2) Java Thread Example by implementing Runnable interface


FileName: Multi3.java

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor
Thread(Runnable r)
t1.start();
}
}
Output:

thread is running...
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the
constructors defined above.

FileName: MyThread1.java

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor
Thread(String name)
Thread t= new Thread("My first thread");

// the start() method moves the thread to the active state


t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)


Observe the following program.

FileName: MyThread2.java

public class MyThread2 implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ...");
}

// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();

// creating an object of the class Thread using Thread(Runnable r,


String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();

// getting the thread name by invoking the getName() method


String str = th1.getName();
System.out.println(str);
}
}
Output:

My new thread
Now the thread is running ...
Sample code to create Thread by using Runnable Interface:

import java.io.*;
import java.util.*;

public class GFG implements Runnable {


// method to start Thread
public void run()
{
System.out.println(
"Thread is Running Successfully");
}

public static void main(String[] args)


{
GFG g1 = new GFG();
// initializing Thread Object
Thread t1 = new Thread(g1);
t1.start();
}
}
Output
Thread is Running Successfully

Sample Code to create Thread in Java using Thread(String name):

Java
1
import java.io.*;
2
import java.util.*;
3

4
public class GFG {
5
public static void main(String args[])
6
{
7
// Thread object created
8
// and initiated with data
9
Thread t = new Thread("Hello Geeks!");
10

11
// Thread gets started
12
t.start();
13

14
// getting data of
15
// Thread through String
16
String s = t.getName();
17
System.out.println(s);
18
}
19
}

Output
Hello Geeks!

Sample Java Code which creates Thread Object by using


Thread(Runnable r, String name):

Java
1
import java.io.*;
2
import java.util.*;
3

4
public class GFG implements Runnable {
5
public void run()
6
{
7
System.out.println(
8
"Thread is created and running successfully...");
9
}
10
public static void main(String[] args)
11
{
12
// aligning GFG Class with
13
// Runnable interface
14
Runnable r1 = new GFG();
15
Thread t1 = new Thread(r1, "My Thread");
16
// Thread object started
17
t1.start();
18
// getting the Thread
19
// with String Method
20
String str = t1.getName();
21
System.out.println(str);
22
}
23
}

Output
My Thread
Thread is created and running successfully...

Java Program to explore different Thread States:

Let us see the working of thread states by implementing them on Threads


t1 and t2.

Output:

Java
1
import java.io.*;
2
import java.util.*;
3

4
class GFG implements Runnable {
5
public void run()
6
{
7
// implementing try-catch Block to set sleep state
8
// for inactive thread
9
try {
10
Thread.sleep(102);
11
}
12
catch (InterruptedException i1) {
13
i1.printStackTrace();
14
}
15
System.out.println(
16
"The state for t1 after it invoked join method() on
thread t2"
17
+ " " + ThreadState.t1.getState());
18

19
// implementing try-catch block
20
try {
21
Thread.sleep(202);
22
}
23
catch (InterruptedException i2) {
24
i2.printStackTrace();
25
}
26
}
27
}
28

29
// creation of ThreadState class
30
// to implement Runnable interface
31
public class ThreadState implements Runnable {
32
public static Thread t1;
33
public static ThreadState o1;
34
public static void main(String args[])
35
{
36
o1 = new ThreadState();
37
t1 = new Thread(o1);
38
System.out.println("post-spanning, state of t1 is"
39
+ " " + t1.getState());
40
// lets invoke start() method on t1
41
t1.start();
42
// Now,Thread t1 is moved to runnable state
43
System.out.println(
44
"post invoking of start() method, state of t1 is"
45
+ " " + t1.getState());
46
}
47
public void run()
48
{
49
GFG g1 = new GFG();
50
Thread t2 = new Thread(g1);
51
// Thread is created and its in new state.
52
t2.start();
53
// Now t2 is moved to runnable state
54
System.out.println(
55
"state of t2 Thread, post-calling of start() method
is"
56
+ " " + t2.getState());
57
// create a try-catch block to set t1 in waiting
58
// state
59
try {
60
Thread.sleep(202);
61
}
62
catch (InterruptedException i2) {
63
i2.printStackTrace();
64
}
65
System.out.println(
66
"State of Thread t2 after invoking to method sleep()
is"
67
+ " " + t2.getState());
68
try {
69
t2.join();
70
System.out.println(
71
"State of Thread t2 after join() is"
72
+ " " + t2.getState());
73
}
74
catch (InterruptedException i3) {
75
i3.printStackTrace();
76
}
77
System.out.println(
78
"state of Thread t1 after completing the execution
is"
79
+ " " + t1.getState());
80
}
81
}

Output
post-spanning, state of t1 is NEW
post invoking of start() method, state of t1 is RUNNABLE
state of t2 Thread, post-calling of start() method is RUNNABLE
The state for t1 after it invoked join method() on thread t2
TIMED_WAITING
State of Thread t2 after invoking to method sleep() is
TIMED_WAITING
State of Thread t2 after join() is TERMINATED
state of Thread t1 after completing the execution is RUNNABLE

Running Threads
If the class extends the Thread class, the thread can be run by creating
an instance of the class and call its start() method:

Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
OUTPUT
This code is outside of the thread
This code is running in a thread

If the class implements the Runnable interface, the thread can be run by
passing an instance of the class to a Thread object's constructor and
then calling the thread's start() method:

Implement Example
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}

OUTPUT
This code is outside of the thread
This code is running in a thread

Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you
cannot extend any other class, but by implementing the Runnable
interface, it is possible to extend from another class as well, like: class
MyClass extends OtherClass implements Runnable.

You might also like