Home | Thread Priorities

Chapter: Web or internet Programming : JAVA

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10).

Thread Priorities:

 

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

 

Threads with higher priority are more important to a program and should be allocated processor time before lower- priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependant.

 

 

Create Thread by Implementing Runnable Interface:

 

 

If your class is intended to be executed as a thread then you can achieve this by implementing Runnable interface. You will need to follow three basic steps:

 

 

Step 1:

 

As a first step you need to implement a run() method provided by Runnable interface. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax ofrun() method:

 

public void run( )

 

Step 2:

 

At second step you will instantiate a Thread object using the following constructor:

 

Thread(Runnable threadObj, String threadName);

 

Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.

 

Step 3

 

Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:

 

void start( );

 

Here is an example that creates a new thread and starts it running:

class RunnableDemo implements Runnable {     

private        Thread        t;                          

private        String          threadName;                           

RunnableDemo( String name){                 

threadName = name;                        

System.out.println("Creating  " +     threadName          );

}                                             

public         void run() {                   

System.out.println("Running  " +     threadName          );

try {                                       

 

for(int i = 4; i > 0; i--) {

 

System.out.println("Thread: " + threadName +  ",  " + i);

 

// Let the thread sleep  for       a while.

Thread.sleep(50);

}       

 

} catch (InterruptedException e) {            

System.out.println("Thread    " +     threadName          +       " interrupted.");

}                                   

System.out.println("Thread    " +     threadName          +       " exiting.");

}                                   

public void start () {                                  

System.out.println("Starting   " +     threadName          );      

if(t== null)                              

{                                   

 

t= new Thread (this, threadName); t.start ();

 

}   } }

 

public class TestThread  {

 

public static void main(String args[]) {

 

 

RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start();

 

 

RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start();

 

}

 

}

 

 

This would produce the following result:

 

 

Creating Thread-1

 

Starting Thread-1

 

Creating Thread-2

 

Starting Thread-2

 

Running Thread-1

 

Thread: Thread-1, 4

 

Running Thread-2         

Thread: Thread-2, 4      

Thread: Thread-1, 3      

Thread: Thread-2, 3      

Thread: Thread-1, 2      

Thread: Thread-2, 2      

Thread: Thread-1, 1      

Thread: Thread-2, 1      

Thread Thread-1 exiting. Thread Thread-2 exiting.      

Create Thread by Extending Thread Class:

 

The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

 

Step 1

 

You will need to override run( ) method available in Thread class. This method provides entry point for the thread and you will put you complete business logic inside this method. Following is simple syntax of run() method:

 

public void run( )

 

Step 2

 

Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( ) method. Following is simple syntax of start() method:

 

void start( );

 

 

Here is the preceding program rewritten to extend Thread:

 

 

class ThreadDemo extends Thread {

 

 

private Thread t;

 

private String threadName;

 

ThreadDemo( String name){                     

threadName = name;                        

System.out.println("Creating  " +     threadName          );

}                          

public void run() {                           

System.out.println("Running  " +     threadName          );

 

try {                                        

for(int i = 4; i >    0; i--) {                                    

System.out.println("Thread: " + threadName +  ",  " + i);

// Let the thread    sleep  for     a while.                

Thread.sleep(50);                                       

}                                             

} catch (InterruptedException e) {             

System.out.println("Thread    " +     threadName          +       " interrupted.");

}                                             

System.out.println("Thread    " +     threadName          +       " exiting.");

}                                             

 

 

public void start ()

 

{

 

System.out.println("Starting " + threadName ); if(t== null)

 

{

 

t= new Thread (this, threadName); t.start ();

 

}   }   }

 

 

public class TestThread  {

 

public static void main(String args[]) {

 

 

ThreadDemo T1 = new  ThreadDemo(  "Thread-1"); T1.start();

ThreadDemo T2 = new  ThreadDemo(  "Thread-2"); T2.start();

 

}   }

 

 

This would produce the following result:

 

 

Creating Thread-1

 

Starting Thread-1

 

Creating Thread-2

 

Starting Thread-2

 

Running Thread-1

 

Thread: Thread-1, 4

 

Running Thread-2

 

Thread: Thread-2, 4

 

Thread: Thread-1, 3

 

Thread: Thread-2, 3

 

Thread: Thread-1, 2

 

Thread: Thread-2, 2

 

Thread: Thread-1, 1

 

Thread: Thread-2, 1

 

Thread Thread-1 exiting. Thread Thread-2 exiting.

 

Thread Methods:

 

public void start(): Starts the thread in a separate path ofexecution, then invokes the run() method on this Thread object.

 

public void run(): If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.

 

public final void setName(String name): Changes the name ofthe Thread object. There is also a getName() method for retrieving the name.

 

public final void setPriority(int priority): Sets the priority of this Thread object. The possible

 

values are between 1 and 10.

 

 

public final void join(long millisec): The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

 

public void interrupt(): Interrupts this thread, causing it to continue execution ifit was blocked

 

for any reason.

 

public final boolean isAlive(): Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

 

 


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : JAVA : Thread Priorities |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.