3:51 am - Monday June 25, 2018

Threads in java with Example Program

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

THREADS:

Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class.

An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:

Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:


public class MyRunnable implements Runnable {

public void run() {

System.out.println("Hello from a thread!");

}

public static void main(String args[]) {

(new Thread(new HelloRunnable())).start();

}

}

Subclass Thread: The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:


public class MyThread extends Thread {

public void run() {

System.out.println("Hello from a thread!");

}

public static void main(String args[]) {

(new HelloThread()).start();

}

}

Notice that both examples invoke Thread.start in order to start the new thread.

//starting Thread

          Thread mythread = new MyThread();
          mythread.setName("T1");
          Thread myrunnable = new Thread(new MyRunnable(),"T2");
          mythread.start();
          myrunnable.start();

Life Cycle Of Thread:

New born stage: in this stage the thread is newly created and has not been started yet. You can see by diagram that this is first stage of all the thread, before start any thread; it has to crate the instance of thread. You can directly go to either dead or active stage from new born stage.

Active stage:  this is the stage where thread executes. A thread can be come in active stage only by new born stage.

Any thread can be come in active stage by calling start () method of that thread

Being in the active stage does not mean that thread is running, because there may be chance that

There is more thread which has the high priority than yours thread.

In active stage there is two more stages called as Running and Runnable stage.

Running stage: This is the stage where thread executes actually. It is thread shoulder responsibility to decide which thread should execute first. At a time only one thread can be in this stage, all other active thread will be in Runnable stage waiting for their execution time.

Runnable stage: this is the active stage where the threads are waiting for their term for execution.

You can move any thread from Running stage to Runnable stage by using yaield() method of thread class.

Blocked stage: This is the stage where the thread has to block for execution, from this stage a thread can be come back to active stage and can be directly send to dead stage.

There are some methods in thread which can be cause thread to go into blocked thread.

Wait(), suspend() and sleep() are method which can be used to bring thread into blocked stage.

To come back into active stage you have to use notify() or notifyAll() if thread came by wait() method in blocked stage.

To come back into active stage you have to use resume() method if thread came by suspend() method of thread.

The thread will come back automatically into active stage if time over given in milliseconds if thread came by sleep() method.

Dead stage: this is the last stage of thread life cycle. A thread has to come in dead stage if it has finished execution, you can explicitly bring a thread to dead stage from any other stage by using stop() method of thread class.

start()                                    – To Start a new Thread.
suspend()                              – To suspend a started thread
resume()                                – To Resume a suspended thread
stop()                                     – To stop current running thread.
sleep(int m)/sleep(int m,int n)– The thread sleeps for m milliseconds, plus n nanoseconds.
Yield()                                     – To pause current running thread a give a chance to any other thread.
Join()                                      – To complete the execution of current running thread.

 

Example :Join Thread

 //Use Of Join
 class Thread3 extends Thread
 {
     public void run()
     {
         for(int i=1;i<=5;i++)
         {
             try{
             Thread.sleep(500);
             System.out.println("From Thread 1:"+i);
             //t1.join();
             }catch(InterruptedException i3){System.out.println("FF");}
         }
     }
 }
 class Thread4 extends Thread
 {
     public void run()
     {
         for(int i=1;i<=5;i++)
         {
                 try
                 {
                     Thread.sleep(500);
                     System.out.println("From Thread 2:"+i);
                 }catch(InterruptedException i2){System.out.println("GG");}

         }
     }
 }
 class UseJoin
 {
     public static void main(String ss[])
     {
         try{
         Thread t1=new Thread(new Thread3());
         Thread t3=new Thread(new Thread3());
         Thread t2=new Thread(new Thread4());
         t1.start();
         t1.join();
         t2.start();
         t2.join();
         t3.start();
         t3.join();
         for(int i=1;i<=5;i++)
         {
                 try
                 {
                     Thread.sleep(500);
                     System.out.println("From Main:"+i);
                 }catch(InterruptedException i2){System.out.println("GG");}

         }
         }catch(InterruptedException i2){System.out.println("GG");}
     }
 }
 

Benefits of multithreading

Thread States

Thread Safety

Deadlocked Threads

Filed in: Z-A All Java Codes

No comments yet.

Leave a Reply