Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Multithreading in Java

Uploaded by

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

Multithreading in Java

Uploaded by

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

Multithreading in Java

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

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.
Note: 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.

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
S.N. Modifier and Type Method Description

It is used to start the execution of the


1) void start()
thread.

It is used to do an action for a


2) void run()
thread.

It sleeps a thread for the specified


3) static void sleep()
amount of time.

It returns a reference to the currently


4) static Thread currentThread()
executing thread object.

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


6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

It causes the currently executing


12) static void yield() thread object to pause and allow
other threads to execute temporarily.

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

It is used to resume the suspended


14) void resume()
thread.

15) void stop() It is used to stop the thread.

It is used to destroy the thread group


16) void destroy()
and all of its subgroups.

It tests if the thread is a daemon


17) boolean isDaemon()
thread.

It marks the thread as daemon or


18) void setDaemon()
user thread.

19) void interrupt() It interrupts the thread.

It tests whether the thread has been


20) boolean isinterrupted()
interrupted.

It tests whether the current thread


21) static boolean interrupted()
has been interrupted.

It returns the number of active


22) static int activeCount() threads in the current thread's thread
group.

It determines if the currently running


23) void checkAccess() thread has permission to modify the
thread.

It returns true if and only if the


24) static boolean holdLock() current thread holds the monitor lock
on the specified object.

It is used to print a stack trace of the


25) static void dumpStack() current thread to the standard error
stream.

It returns an array of stack trace


26) StackTraceElement[] getStackTrace() elements representing the stack
dump of the thread.

It is used to copy every active


27) static int enumerate() thread's thread group and its
subgroup into the specified array.

It is used to return the state of the


28) Thread.State getState()
thread.

It is used to return the thread group


29) ThreadGroup getThreadGroup()
to which this thread belongs

It is used to return a string


representation of this thread,
30) String toString()
including the thread's name, priority,
and thread group.

It is used to give the notification for


31) void notify() only one thread which is waiting for a
particular object.

It is used to give the notification to all


32) void notifyAll()
waiting threads of a particular object.
It sets the context ClassLoader for
33) void setContextClassLoader()
the Thread.

It returns the context ClassLoader


34) ClassLoader getContextClassLoader()
for the thread.

It returns the default handler invoked


static
35) getDefaultUncaughtExceptionHandler() when a thread abruptly terminates
Thread.UncaughtExceptionHandler
due to an uncaught exception.

It sets the default handler invoked


36) static void setDefaultUncaughtExceptionHandler() when a thread abruptly terminates
due to an uncaught exception.

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
Explanation of Different Thread States
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.
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.
o 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.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a
short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that
the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run,
waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o 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.
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.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which thread to choose and which
one to reject, and the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is
not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid
such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real
example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state.
After the time runs out, the thread wakes up and start its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active
after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States


In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java provides the
constants ENUM to represent the state of a thread. These constants are:
1. public static final Thread.State NEW
It represents the first state of a thread that is the NEW state.
1. public static final Thread.State RUNNABLE
It represents the runnable state.It means a thread is waiting in the queue to run.
1. public static final Thread.State BLOCKED
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
1. public static final Thread.State WAITING
It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or Thread.join() method with no timeout. A
thread in the waiting state is waiting for another thread to complete its task.
1. public static final Thread.State TIMED_WAITING
It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint. Waiting has no time constraint,
whereas timed waiting has the time constraint. A thread invoking the following method reaches the timed waiting state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos
1. public static final Thread.State TERMINATED
It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its execution.
Java Program for Demonstrating Thread States
The following Java program shows some of the states of a thread defined above.
FileName: ThreadState.java
1. // ABC class implements the interface Runnable
2. class ABC implements Runnable
3. {
4. public void run()
5. {
6.
7. // try-catch block
8. try
9. {
10. // moving thread t2 to the state timed waiting
11. Thread.sleep(100);
12. }
13. catch (InterruptedException ie)
14. {
15. ie.printStackTrace();
16. }
17.
18.
19. System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ ThreadState.t1.getState());
20.
21. // try-catch block
22. try
23. {
24. Thread.sleep(200);
25. }
26. catch (InterruptedException ie)
27. {
28. ie.printStackTrace();
29. }
30. }
31. }
32.
33. // ThreadState class implements the interface Runnable
34. public class ThreadState implements Runnable
35. {
36. public static Thread t1;
37. public static ThreadState obj;
38.
39. // main method
40. public static void main(String argvs[])
41. {
42. // creating an object of the class ThreadState
43. obj = new ThreadState();
44. t1 = new Thread(obj);
45.
46. // thread t1 is spawned
47. // The thread t1 is currently in the NEW state.
48. System.out.println("The state of thread t1 after spawning it - " + t1.getState());
49.
50. // invoking the start() method on
51. // the thread t1
52. t1.start();
53.
54. // thread t1 is moved to the Runnable state
55. System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
56. }
57.
58. public void run()
59. {
60. ABC myObj = new ABC();
61. Thread t2 = new Thread(myObj);
62.
63. // thread t2 is created and is currently in the NEW state.
64. System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
65. t2.start();
66.
67. // thread t2 is moved to the runnable state
68. System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());
69.
70. // try-catch block for the smooth flow of the program
71. try
72. {
73. // moving the thread t1 to the state timed waiting
74. Thread.sleep(200);
75. }
76. catch (InterruptedException ie)
77. {
78. ie.printStackTrace();
79. }
80.
81. System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );
82.
83. // try-catch block for the smooth flow of the program
84. try
85. {
86. // waiting for thread t2 to complete its execution
87. t2.join();
88. }
89. catch (InterruptedException ie)
90. {
91. ie.printStackTrace();
92. }
93. System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());
94. }
95.
96. }
Output:

The state of thread t1 after spawning it - NEW


The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED

Explanation: Whenever we spawn a new thread, that thread attains the new state. When the method start() is invoked on a thread, the thread
scheduler moves that thread to the runnable state. Whenever the join() method is invoked on any thread instance, the current thread executing that
statement has to wait for this thread to finish its execution, i.e., move that thread to the terminated state. Therefore, before the final print statement
is printed on the console, the program invokes the method join() on thread t2, making the thread t1 wait while the thread t2 finishes its execution
and thus, the thread t2 get to the terminated or dead state. Thread t1 goes to the waiting state because it is waiting for thread t2 to finish it's
execution as it has invoked the method join() on thread t2.
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:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o 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 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.
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:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o 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
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:

thread is running...

2) Java Thread Example by implementing Runnable interface


FileName: Multi3.java
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }
Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread object. So you need to explicitly create the Thread
class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.
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
1. public class MyThread1
2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }
Output:

My first thread

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


Observe the following program.
FileName: MyThread2.java
1. public class MyThread2 implements Runnable
2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }
24. }
Output:

My new thread
Now the thread is running ...
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread
class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object.
/ Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a
Thread object and call start() method on this object.

 Java
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple
inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods
like yield(), interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst multiple threads.
A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states
at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at any instant in time.

Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the
thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might actually be
running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to give the
thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a
short while and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run.
When this happens, all such threads that are ready to run, waiting for the CPU and the currently running thread lie in a
runnable state.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock 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.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will move to the
runnable state when other thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread lies in
this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a
conditional wait, it is moved to a timed waiting state.
6. Terminated State: A thread terminates because of either of the following reasons:

 Because it exits normally. This happens when the code of the thread has been entirely executed by the program.
 Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.
Implementing the Thread States in Java
In Java, to get the current state of the thread, use Thread.getState() method to get the current state of the thread. Java
provides java.lang.Thread.State class that defines the ENUM constants for the state of a thread, as a summary of which
is given below:
1. New
Thread state for a thread that has not yet started.
public static final Thread.State NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be
waiting for other resources from the operating system such as a processor.
public static final Thread.State RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to
enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait().
public static final Thread.State BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:
 Object.wait with no timeout
 Thread.join with no timeout
 LockSupport.park
public static final Thread.State WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of
the following methods with a specified positive waiting time:
 Thread.sleep
 Object.wait with timeout
 Thread.join with timeout
 LockSupport.parkNanos
 LockSupport.parkUntil
public static final Thread.State TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed execution.
Declaration: public static final Thread.State TERMINATED
Example
Below is the implementation of the thread states mentioned above:
1
// Java program to demonstrate thread states
2
class thread implements Runnable {
3
public void run()
4
{
5
// moving thread2 to timed waiting state
6
try {
7
Thread.sleep(1500);
8
}
9
catch (InterruptedException e) {
10
e.printStackTrace();
11
}
12

13
System.out.println(
14
"State of thread1 while it called join() method on thread2 -"
15
+ Test.thread1.getState());
16
try {
17
Thread.sleep(200);
18
}
19
catch (InterruptedException e) {
20
e.printStackTrace();
21
}
22
}
23
}
24

25
public class Test implements Runnable {
26
public static Thread thread1;
27
public static Test obj;
28

29
public static void main(String[] args)
30
{
31
obj = new Test();
32
thread1 = new Thread(obj);
33

34
// thread1 created and is currently in the NEW
35
// state.
36
System.out.println(
37
"State of thread1 after creating it - "
38
+ thread1.getState());
39
thread1.start();
40

41
// thread1 moved to Runnable state
42
System.out.println(
43
"State of thread1 after calling .start() method on it - "
44
+ thread1.getState());
45
}
46

47
public void run()
48
{
49
thread myThread = new thread();
50
Thread thread2 = new Thread(myThread);
51

52
// thread2 created and is currently in the NEW
53
// state.
54
System.out.println(
55
"State of thread2 after creating it - "
56
+ thread2.getState());
57
thread2.start();
58

59
// thread2 moved to Runnable state
60
System.out.println(
61
"State of thread2 after calling .start() method on it - "
62
+ thread2.getState());
63

64
// moving thread2 to timed waiting state
65
try {
66
// moving thread2 to timed waiting state
67
Thread.sleep(200);
68
}
69
catch (InterruptedException e) {
70
e.printStackTrace();
71
}
72
System.out.println(
73
"State of thread2 after calling .sleep() method on it - "
74
+ thread2.getState());
75

76
try {
77
// waiting for thread2 to die
78
thread2.join();
79
}
80
catch (InterruptedException e) {
81
e.printStackTrace();
82
}
83
System.out.println(
84
"State of thread2 when it has finished it's execution - "
85
+ thread2.getState());
86
}
87
}

Output
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it - RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it - RUNNABLE
State of thread2 after calling .sleep() method on it - TIMED_WAITING
State of thread1 while it called join() method on thread2 -WAITING
State of thread2 when it has finished it's execution - TERMINATED
Explanation of the above Program
When a new thread is created, the thread is in the NEW state. When the start() method is called on a thread, the thread
scheduler moves it to the Runnable state. Whenever the join() method is called on a thread instance, the current thread
executing that statement will wait for this thread to move to the Terminated state. So, before the final statement is printed
on the console, the program calls join() on thread2 making the thread1 wait while thread2 completes its execution and is
moved to the Terminated state. thread1 goes to the Waiting state because it is waiting for thread2 to complete its
execution as it has called join on thread2.
Java Thread Priority in Multithreading
Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while
creating the thread or it can be given by the programmer explicitly.
Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every
object is having priority here which is represented by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 1.
 Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
Let us discuss it with an example to get how internally the work is getting executed. Here we will be using the knowledge
gathered above as follows:
 We will use currentThread() method to get the name of the current thread. User can also use setName() method if
he/she wants to make names of thread as per choice for understanding purposes.
 getName() method will be used to get the name of the thread.
The accepted value of priority for a thread is in the range of 1 to 10.
Let us do discuss how to get and set priority of a thread in java.
1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method changes the priority of thread to
the value newPriority. This method throws IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.
Example
Java

// Java Program to Illustrate Priorities in Multithreading

// via help of getPriority() and setPriority() method

import java.lang.*;

// Main class

class ThreadDemo extends Thread {

// Method 1

// run() method for the thread that is called

// as soon as start() is invoked for thread in main()

public void run()

{ // Print statement

System.out.println("Inside run method");

}
// Main driver method

public static void main(String[] args)

{ // Creating random threads with the help of above class

ThreadDemo t1 = new ThreadDemo();

ThreadDemo t2 = new ThreadDemo();

ThreadDemo t3 = new ThreadDemo();

// Thread 1

// Display the priority of above thread using getPriority() method

System.out.println("t1 thread priority : "+ t1.getPriority());

// Thread 1 Display the priority of above thread

System.out.println("t2 thread priority : " + t2.getPriority());

// Thread 3

System.out.println("t3 thread priority : " + t3.getPriority());

// Setting priorities of above threads by passing integer arguments

t1.setPriority(2);

t2.setPriority(5);

t3.setPriority(8);

// t3.setPriority(21); will throw IllegalArgumentException

// 2

System.out.println("t1 thread priority : " + t1.getPriority());

// 5

System.out.println("t2 thread priority : " + t2.getPriority());

// 8

System.out.println("t3 thread priority : " + t3.getPriority());

// Main thread Displays the name of currently executing Thread

System.out.println("Currently Executing Thread : " +


Thread.currentThread().getName());

System.out.println("Main thread priority : " +


Thread.currentThread().getPriority());

// Main thread priority is set to 10

Thread.currentThread().setPriority(10);

System.out.println("Main thread priority : "

+ Thread.currentThread().getPriority());

Output

t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:
 Thread with the highest priority will get an execution chance prior to other threads. Suppose there are 3 threads t1, t2,
and t3 with priorities 4, 6, and 1. So, thread t2 will execute first based on maximum priority 6 after that t1 will execute
and then t3.
 The default priority for the main thread is always 5, it can be changed later. The default priority for all other threads
depends on the priority of the parent thread.
Now geeks you must be wondering out what if we do assign the same priorities to threads then what will happen. All the
processing in order to look after threads is carried with help of the thread scheduler. One can refer to the below example
of what will happen if the priorities are set to the same and later onwards we will discuss it as an output explanation to
have a better understanding conceptually and practically.
Example
Java

// Java program to demonstrate that a Child thread

// Getting Same Priority as Parent thread

// Importing all classes from java.lang package

import java.lang.*;
// Main class

// ThreadDemo

// Extending Thread class

class GFG extends Thread {

// Method 1

// run() method for the thread that is

// invoked as threads are started

public void run()

{ // Print statement

System.out.println("Inside run method");

// Method 2

// Main driver method

public static void main(String[] args)

{ // main thread priority is set to 6 now

Thread.currentThread().setPriority(6);

// Current thread is accessed

// using currentThread() method

// Print and display main thread priority

// using getPriority() method of Thread class

System.out.println(

"main thread priority : "

+ Thread.currentThread().getPriority());

// Creating a thread by creating object inside

// main()

GFG t1 = new GFG();

// t1 thread is child of main thread

// so t1 thread will also have priority 6


// Print and display priority of current thread

System.out.println("t1 thread priority : " + t1.getPriority());

} }

Output

main thread priority : 6


t1 thread priority : 6
Output explanation:
 If two threads have the same priority then we can’t expect which thread will execute first. It depends on the thread
scheduler’s algorithm(Round-Robin, First Come First Serve, etc)
 If we are using thread priority for thread scheduling then we should always keep in mind that the underlying platform
should provide support for scheduling based on thread priority.
Objective-type questions on Multithreading in Java:

1. What is multithreading in Java?

A. Executing multiple processes simultaneously


B. Executing multiple threads concurrently
C. Executing a single thread multiple times
D. None of the above

2. Which class is used to create threads in Java?

A. Runnable
B. Thread
C. Executor
D. ThreadPool

3. Which method is used to start a thread in Java?

A. run()
B. begin()
C. start()
D. execute()

4. The Runnable interface contains which method?

A. run()
B. start()
C. execute()
D. begin()

5. Which package provides classes for Java multithreading?

A. java.util
B. java.thread
C. java.lang
D. java.concurrent

6. What is the default priority of a thread in Java?

A. 0
B. 1
C. 5
D. 10
7. Which method is used to pause a thread for a specific time?

A. wait()
B. sleep()
C. pause()
D. halt()

8. What happens if start() is called on the same thread object twice?

A. Runs successfully
B. Throws IllegalThreadStateException
C. Creates a new thread
D. Restarts the thread

9. How can a thread be stopped in Java?

A. Using stop()
B. Using interrupt()
C. Using sleep()
D. Threads cannot be stopped

10. Which method is called to execute code in a thread?

A. run()
B. start()
C. call()
D. execute()

11. Threads in Java are implemented using which model?

A. Kernel-level threads
B. User-level threads
C. Both kernel and user-level threads
D. Hybrid threads

12. What is a daemon thread?

A. A thread that is always running


B. A thread that runs in the background
C. A thread that runs with maximum priority
D. A thread that cannot be terminated
13. How is a thread set as a daemon thread?

A. Using setPriority()
B. Using setDaemon(true)
C. Using startDaemon()
D. By creating it in the main thread

14. Which method checks if a thread is alive?

A. isAlive()
B. checkStatus()
C. isRunning()
D. threadState()

15. What does the join() method do?

A. Merges two threads into one


B. Stops a thread
C. Waits for a thread to complete
D. Starts a thread

16. What is thread synchronization?

A. Running multiple threads at the same time


B. Controlling thread execution order
C. Allowing only one thread to access a resource at a time
D. Merging multiple threads

17. Which keyword is used for synchronization in Java?

A. synchronized
B. static
C. volatile
D. thread-safe

18. What is a thread pool?

A. A collection of threads for a task


B. A pool of threads running at the same time
C. A group of terminated threads
D. None of the above
19. Which class provides thread pooling in Java?

A. ThreadGroup
B. Thread
C. Executor
D. Future

20. What does the wait() method do?

A. Stops a thread
B. Waits for a thread to start
C. Causes a thread to wait until notified
D. Suspends a thread

21. Which method notifies a waiting thread?

A. notifyAll()
B. notify()
C. start()
D. Both A and B

22. What is the state of a thread after calling yield()?

A. Blocked
B. Waiting
C. Runnable
D. Terminated

23. Which method is used to check if a thread is interrupted?

A. checkInterrupt()
B. isInterrupted()
C. threadInterrupted()
D. interrupted()

24. Which of the following is a thread state?

A. Ready
B. Waiting
C. Terminated
D. All of the above
25. How many threads can be run at a time in Java?

A. One
B. Two
C. Depends on CPU
D. Unlimited

26. What is the ThreadGroup class used for?

A. Grouping threads for collective management


B. Synchronizing threads
C. Running threads in parallel
D. Terminating all threads

27. Which method is used to prioritize threads?

A. setThreadPriority()
B. setPriority()
C. prioritizeThread()
D. setPriorityLevel()

28. Can a thread be restarted once terminated?

A. Yes
B. No
C. Only if it’s a daemon thread
D. Only if set as runnable

29. What does the volatile keyword ensure in multithreading?

A. Synchronized access to a variable


B. Variable is stored in CPU cache
C. Variable is read directly from memory
D. Variable cannot be changed

30. What happens if a thread is interrupted during sleep?

A. Thread continues sleeping


B. Throws InterruptedException
C. Terminates the thread
D. Runs the thread immediately
Answers to the Above objective-type questions:

1. What is multithreading in Java?


B. Executing multiple threads concurrently

2. Which class is used to create threads in Java?


B. Thread

3. Which method is used to start a thread in Java?


C. start()

4. The Runnable interface contains which method?


A. run()

5. Which package provides classes for Java multithreading?


C. java.lang

6. What is the default priority of a thread in Java?


C. 5

7. Which method is used to pause a thread for a specific time?


B. sleep()

8. What happens if start() is called on the same thread object twice?


B. Throws IllegalThreadStateException
9. How can a thread be stopped in Java?
B. Using interrupt()
(Deprecated methods like stop() are no longer recommended.)

10. Which method is called to execute code in a thread?


A. run()

11. Threads in Java are implemented using which model?


C. Both kernel and user-level threads

12. What is a daemon thread?


B. A thread that runs in the background

13. How is a thread set as a daemon thread?


B. Using setDaemon(true)

14. Which method checks if a thread is alive?


A. isAlive()

15. What does the join() method do?


C. Waits for a thread to complete

16. What is thread synchronization?


C. Allowing only one thread to access a resource at a time

17. Which keyword is used for synchronization in Java?


A. synchronized

18. What is a thread pool?


A. A collection of threads for a task

19. Which class provides thread pooling in Java?


C. Executor
20. What does the wait() method do?
C. Causes a thread to wait until notified

21. Which method notifies a waiting thread?


D. Both A and B (notify() and notifyAll())

22. What is the state of a thread after calling yield()?


C. Runnable

23. Which method is used to check if a thread is interrupted?


B. isInterrupted()

24. Which of the following is a thread state?


D. All of the above

25. How many threads can be run at a time in Java?


C. Depends on CPU

26. What is the ThreadGroup class used for?


A. Grouping threads for collective management

27. Which method is used to prioritize threads?


B. setPriority()

28. Can a thread be restarted once terminated?


B. No

29. What does the volatile keyword ensure in multithreading?


C. Variable is read directly from memory

30. What happens if a thread is interrupted during sleep?


B. Throws InterruptedException
Questions

1. A thread in Java can be created by extending the ______ class or implementing the ______ interface.
Answer: Thread, Runnable
2. The ______ method is used to start the execution of a thread.
Answer: start()
3. The keyword ______ is used to ensure that a block of code is accessed by only one thread at a time.
Answer: synchronized
4. A thread that runs in the background and performs tasks such as garbage collection is called a
______ thread.
Answer: daemon
5. The ______ method causes the current thread to temporarily pause its execution and allow other
threads to execute.
Answer: yield()
6. The ______ method is used to make a thread wait until it is notified.
Answer: wait()
7. The default priority of a thread in Java is ______.
Answer: 5
8. The ______ method is used to check if a thread is alive.
Answer: isAlive()
9. The ______ class in the java.util.concurrent package is used to create thread pools.
Answer: Executor
10. The ______ method in Java interrupts a thread that is currently sleeping or waiting.
Answer: interrupt()
Match-the-following activity :-

Column A (Questions) Column B (Descriptions)

1. start() A. Method to make a thread wait until notified


2. run() B. Used to check if a thread is still running
3. synchronized C. Method that initiates a new thread
4. Daemon thread D. Keyword to allow only one thread to access a resource
5. Executor E. Background thread used for low-priority tasks
6. join() F. Method that waits for a thread to finish
7. isAlive() G. Causes the current thread to pause and allow others to execute
8. yield() H. Used to interrupt a thread’s sleep or wait
9. wait() I. The class that provides thread pooling functionality
10. interrupt() J. Method that defines the task a thread will execute

Answers

1. start() → C
2. run() → J
3. synchronized → D
4. Daemon thread → E
5. Executor → I
6. join() → F
7. isAlive() → B
8. yield() → G
9. wait() → A
10. interrupt() → H

You might also like