Share on Google+Share on Google+

Java :Thread setPriority Example

Advertisement
In this tutorial you will learn how to set thread priority in java thread.

Java :Thread setPriority Example

In this tutorial you will learn how to set thread priority in java thread.

Thread setPriority() :

Thread scheduler uses thread priority concept to assign priority to the thread. A higher priority  threads execute first then the lower priority threads. You can set priority by using method setPriority ().

public final void setPriority(int newPriority) : This method changes priority of your thread. You can set newPriority ranges from MIN_PRIORITY to MAX_PRIORITY.

Parameters: 
newPriority
- priority to be set to the  thread.

It throws IllegalArgumentException and SecurityException

Example : In this example we are setting thread priority 10 to the current thread.

class ThreadSetPriority implements Runnable {
	Thread thread = new Thread();

	public ThreadSetPriority() {
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		System.out.println("Thread Priority : " + thread.getPriority());
		/* Setting thread priority */
		thread.setPriority(10);
		System.out.println("After setting priority, Thread Priority : "
				+ thread.getPriority());
	}

	public static void main(String[] args) {
		new ThreadSetPriority();

	}

}

Output :

Thread Priority : 5
After setting priority, Thread Priority : 10

Advertisements

Posted on: November 6, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.