Skip to main content

Posts

Showing posts from September, 2008

Thread priority

Thread priorities are integer values between 1 and 10 used by the thread scheduler to assign the CPU time for the thread for execute their task. When many threads are executed by the thread scheduler, then the thread scheduler uses the priority associated with thread to decide that how much CPU time should be assigned for particular thread. The thread having the higher priority will execute fast then lower priority because the CPU time assigned to higher priority thread is more then lower priority thread. Some constants are defined in the thread class for specify the priority values and they can be used to assign the relative priorities among the threads. Those are below with their access specifier and access modifier. public static final int MAX_PRIORITY 10 public static final int MIN_PRIORITY 1 public static final int NORM_PRIORITY 5 The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java platform suppor

Joining the threads

If you want that one thread should waits until another thread return from its running process or it die You can do it by using the join() method. If join method is called then the execution stops on that line of code until the thread on which join() called is died . //join //Author @ Hemraj class  MyThread  extends   Thread {      String  msg;     MyThread( String  msg)     {          this .msg = msg;     }      public   void  run()     {          for ( int  i = 0;i < 10;i ++ )         {                  try             {                 sleep(500);             } catch ( InterruptedException  e){}              System .out.println(i + msg);         }     }  } class  MyThrea {      public   static   void  main( String  ar[])     {          MyThread t1 = new  MyThread( "this is t1" );         t1.start();          for ( int  i = 0;i < 10;i ++ )         {                  try             {                  Thread .sleep(500);                 

Checking the thread’s life (isAlive())

To check whether a particular thread is in live state or not, at any time we use isAlive() method. This method returns true if the thread for which it called is in the living state and it returns false if the thread is not alive. //isAlive  class  MyThread  extends   Thread {      public   void  run()     {          for ( int  i = 0;i < 10;i ++ )         {                  try             {                 sleep(500);             } catch ( InterruptedException  e){}         }     }  } class  MyThreadTest {      public   static   void  main( String  ar[])     {          System .out.println( "Start main" );         MyThread t1 = new  MyThread();         t1.start();          for ( int  i = 0;i < 12;i ++ )         {                  try             {                  Thread .sleep(1000);             } catch ( InterruptedException  e){}              if (t1.isAlive())                  System .out.println( "t1 is Alive" );