Threading tutorial:Multi-threading in Java

Overview

Threads are simply subprograms those can be  executed simultaneously  with shared memory space.A java process can contain multiple threads.Each java process has at least one thread  ,the main thread.Multi-threading in Java  is an important and interesting topic to learn.

Multi-threading in Java

Now lets discuss the ways to create individual threads in a Java program.

Creating a thread in Java

Threads can be created in two ways:

1.Extending Thread class

This is done by extending the Thread class in Java and overriding the run method. In the run method we can specify the logic to perform in the new thread. Let us discuss with an example.

The class ThreadSample.java given here is extending the Thread class.In the run method we are just printing the multiples of 5 from 0 to 50 along with the thread name , with an interval of 1 second.

public class ThreadSample extends Thread {
int count = 0;
public ThreadSample() {

}
public void run() {
while (count < 50) { try { count = count + 5; System.out.println("Current thread : " + Thread.currentThread().getName() + " " + "count =" + count); sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } }

Now let us see the main class to test the code.The main method just starts the new thread from the main thread. So there will be two threads the main thread and the child thread. The main thread will wait till the child thread finishes.Remember , we have put our thread logic in run method , but we are not directly invoking the run method by threadSample.run() , instead we are calling threadsample.start(). To start a thread the start method needs to be called . If we call the run() method  directly the method will be executed from the calling thread, but separate thread  will not be created for that task. So for creating new thread the start() method should be used. It is better if you give a name while initializing a thread object. Please check the java doc for Thread class to know about the various constructors.

public class ThreadMain {

public ThreadMain() {
}
public static void main(String[] args) {
ThreadSample threadSample = new ThreadSample();
System.out.println("Current thread : Thread name :" + Thread.currentThread().getName());
threadSample.start();

}
}

Now let us see the output.From the output  we can clearly understand the concept of threading by extending Thread class.

Output

Current thread : Thread name :main

Current thread : Thread-0 count =5

Current thread : Thread-0 count =10

Current thread : Thread-0 count =15

Current thread : Thread-0 count =20

Current thread : Thread-0 count =25

Current thread : Thread-0 count =30

Current thread : Thread-0 count =35

Current thread : Thread-0 count =40

Current thread : Thread-0 count =45

Current thread : Thread-0 count =50

2.Using Runnable interface

A thread can be created by implementing the Runnable interface . This interface is having a run() method. In the method we can put the logic to be performed in the thread.We know multiple overloading is not allowed in Java by extending multiple classes together. While creating a thread  , if we are extending the Thread class , we would not be able to  to extend more classes. So if that class needs to be a business class , extending Thread class would not be a better option to create a Thread. In that case , it is preferable to use the Runnable interface.The example explained earlier in this section is redesigned by implementing the Runnable interface.

public class RunnableSample implements Runnable {
int count = 0;
public RunnableSample() {
}
public void run() {
while (count < 50) { try { count = count + 5; System.out.println("Current thread : " + Thread.currentThread().getName() + " " + "count =" + count); Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(); } } } }

Now let us see the main class to  start the thread. First we need to create a Thread  object using the runnable object created. Then we need to call the start() method to start the new thread.

public class RunnableMain {
public RunnableMain() {
}
public static void main(String[] args) {
RunnableSample runnableSample = new RunnableSample();
System.out.println("Current thread : Thread name :" + Thread.currentThread().getName());
Thread runnableThread = new Thread(runnableSample);
runnableThread.start();
}
}

Now let us see the output.It will be exactly the same as that of the previous example.

Output

Current thread : Thread name :main

Current thread : Thread-0 count =5

Current thread : Thread-0 count =10

Current thread : Thread-0 count =15

Current thread : Thread-0 count =20

Current thread : Thread-0 count =25

Current thread : Thread-0 count =30

Current thread : Thread-0 count =35

Current thread : Thread-0 count =40

Current thread : Thread-0 count =45

Current thread : Thread-0 count =50

Thread Life Cycle

A thread goes through various stages in its entire life time . The stages are listed here.

1)New State : This is  the state of a thread when it is created.

2)Runnable State : When the thread is ready to run.

3)Running State  : When the thread is running

4)Blocked State : When the thread is sleeping or waiting .

5)Dead State : When the thread is finished.

 

See Related Discussions

Concurrency in multi-threading

Communication between threads in Java

Thread Priorities

Join() method in Multit-Threading

The yield() method

The sleep() method

Daemon Threads in Java

Thread pool executor in java

Thread pools in Java

Thread Dead lock in Java

Thread Live lock in Java

2 thoughts on “Threading tutorial:Multi-threading in Java

  1. Its crystal clear now….

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">