. • In Java threads scheduler selects the threads using their prioritie• The thread priority is a simple integer value that can be assigned to the particular thread.These priorities can range from 1 (lowest priority) to 10 (highest priority).
Priorities
.
• In
Java threads scheduler selects the threads using their priorities.
• The
thread priority is a simple integer value that can be assigned to the
particular thread.
• These
priorities can range from 1 (lowest priority) to 10 (highest priority).
• There
are two commonly used functionalities in thread scheduling -
o
setPriority
o
getPriority
• The
function setPriority is used to set the priority to each thread
Thread_Name.setPriority
(priority_val);
Where,
priority_val is a constant value denoting the priority for the thread. It is
defined as follows
1.
MAX_PRIORITY = 10
2.
MIN_PRIORITY = 1
3.
NORM_PRIORITY = 5
• The function
getPriority is used to get the priority of the thread.
Thread_Name.getPriority();
What is Preemption?
• Preemption
is a situation in which when the currently executed thread is suspended
temporarily by the highest priority thread.
• The
highest priority thread always preempts the lowest priority thread.
Let us
see the illustration of thread prioritizing with the help of following example
Java program[Thread_PR_Prog.java]
class A
extends Thread
{
public
void run()
{
System.out.println("Thread
#1");
for(int
i=1;i<=5;i++)
{
System.out.println("\tA:
"+i)
}
System.out.println("\n-----End
of Thread #1-------");
}
}
class B
extends Thread
{
public
void run()
{
System.out.println("Thread
#2");
for(int
k=1;k<=5;k++)
{
System.out.println("\tB:
"+k);
}
System.out.println("\n-----End
of Thread #2-------");
}
}
class
Thread_PR_Prog
{
public
static void main(String[] args)
{
A
obj1=new A();
B
obj2=new B();
obj1.setPriority(1);
obj2.setPriority(10);//highest
priority
System.out.println("Strating
Thread#1");
obj1.start();
System.out.println("Strating
Thread#2");
obj2.start();
}
}
Output
Strating
Thread #1
Strating
Thread#2
Thread
#1
Thread
#2
B: 1
B: 2
B: 3
B: 4
B: 5
Thread 2
preempts the execution of thread 1
-----End
of Thread #2-------
A: 1
A: 2
A: 3
A: 4
A: 5
------End
of Thread #1-------
Program explanation
In above
program,
1) We
have created two threads - the Thread#1 and Thread#2.
2) We
assign highest priority to Thread#2.
3) In
the main function both the threads are started but as the Thread #2 has higher
priority than the Thread#1, the Thread #2 preempts the execution of Thread#1.
4) Thus
Thread #2 completes its execution and then Thread #1 completes.
Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Java Programs | Multithreading - Priorities
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation