Wednesday, November 3, 2010

How to set thread priority in java - tutorial with examples

As an application program may have many Threads ,to run all threads at a time,Thread scheduler is run.Though in theory,higher priority threads get more CPU time than lower priority threads,but in practice CPU time may vary from one operating system to other,on how OS is implementing multitask.

   As a Java programmer you need to be very careful while handling threads,as java is designed to work on different environments of OS,programmer  should be see that all threads will get a chance to run.
This can be achieved by handling threads using Thread priorities...
setting priority :

final void setPriority(int level);
the  level must be within the range MIN_PRIORITY and MAX_PRIORITY ...
Currently MIN_PRIORITY is 1 and MAX_PRIORITY is 10.
default value is NORM_PRIORITY which is 5.

To get priority :
final int getPriority();

To make a Thread wait:


How to know whether thread is running or not? 

Two methods to know Thread is running or not is....
isAlive() ---it returns true when Thread is running
This method is defined by Thread.
final boolean isAlive() 

Another method is join()...
final void join() throws InterruptedException
This method is commonly used than first method.

For  example..
Thread t;
- - - - -
A() th1= new A();
- - - -
- - - -

Here I gave a sample method how to use join().
You can try it by your own.....if you try then you will understand more clearly.
To see how to write a Thread program

To start from beginning : Java tutorials

No comments:

Post a Comment