Advertisement
Method | Description |
---|---|
final void setPriority(int priority) | Sets the priority of a Thread. |
Methods | Description |
---|---|
final int getPriority() |
Returns the priority of a Thread. |
// Java - Program to set and get the priority of a thread
class ThreadRun2 implements Runnable
{
//Entry Point of the new thread.
public void run()
{
//Getting the reference to this thread.
Thread t=Thread.currentThread();
//Getting the default priority of NewThread.
System.out.println("Default priority of "+ t.getName() + " : " + t.getPriority());
//Setting the priority of NewThread to 10.
t.setPriority(Thread.MAX_PRIORITY);
//Getting the name and priority of this thread
System.out.println("Priority of " + t.getName() + " : " + t.getPriority());
}
public static void main(String... ar)
{
ThreadRun2 newTh = new ThreadRun2();
Thread th1= new Thread(newTh, "NewThread");//Calling Thread's constructor & passing the object
//of class that has implemented Runnable interface
//& the name of new thread.
//starting the new thread, calls run() method automatically
th1.start();
}
}
Default priority of NewThread : 5
Priority of NewThread : 10
Advertisement
// Java - Program to set and get the priority of a thread
class ThreadRun2 implements Runnable
{
//Entry Point of the new thread.
public void run()
{
//Getting the reference to this thread.
Thread t=Thread.currentThread();
int total=0;
for(int i=0;i<100000000; i++)
{
total = total +i;
}
System.out.println(t.getName() + " with priority " + t.getPriority() + " has finished its execution with total = "+ total);
}
public static void main(String... ar)
{
//Getting the reference to this thread.
Thread t =Thread.currentThread();
//Setting the name of the main thread
t.setName("Main Thread");
//Setting the priority of Main Thread to minimum priority i.e. 1
t.setPriority(Thread.MIN_PRIORITY);
//Creating the object of our class
ThreadRun2 newTh = new ThreadRun2();
Thread th1= new Thread(newTh, "NewThread");//Calling Thread's constructor & passing the object
//of class that has implemented Runnable interface
//& the name of new thread.
//Setting the priority of NewThread to maximum priority i.e 10.
th1.setPriority(Thread.MAX_PRIORITY);
//starting the new thread, calls run() method automatically
th1.start();
int total=0;
for(int i=0;i<100000000; i++)
{
total = total +i;
}
System.out.println(t.getName() + " with priority " + t.getPriority() + " has finished its execution with total = "+ total);
}
}
NewThread with priority 10 has finished its execution with total = 887459712
Main Thread with priority 1 has finished its execution with total = 887459712
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement