Presentation 1
Presentation 1
Presentation 1
AUTONOMOUS
20B01A0594
20B01A05A5
20B01A05C9
TOPIC : 1 . CREATION OF THREADS
2 . THREAD PRIORITY
INTRODUCTION :
RULES :
MyThread ( ) {
…...............;
…...............;
}
public void run ( ) // must override
{
…...............;
…...............;
}
…...............;
}
public class Example {
public static void main(String[] args) {
MyThread t=new MyThread ( ) ;
…...............;
t.start( );
…...............; } }
A program to create a Thread by Extending class
RULES :
• The thread instance has a constructor which accepts the runnable object. Pass this object as a
parameter to the thread instance.
Here we'll discuss how the Java thread scheduler executes threads on a priority basis.
The thread scheduler uses this integer from each thread to determine which one should be allowed to execute.
2.Types of Priorities :
1. MIN_PRIORITY - 1
2. NORM_PRIORITY - 5
• Java's Thread class provides methods for checking the thread’s priority and for modifying it.
• getpriority()
• Setpriority()
• The setPriority() instance method takes an integer between 1 and 10 for changing the thread's
priority.
• If we pass a value outside the 1-10 range, the method will throw an IllegalArgument Exception.
Example:
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}
Output: