Implement Thread in Java

25 Feb 2011 by

Assume that you understand the differences between Process and Thread. If not please refer to this article (Process vs. Thread). Concurrency can be achieved both in Process and Thread. Developing concurrency process is costly and hard to manage the process behavior since all processes have their own address space. Thread has been motivated in this sense. Thread can take a lot of advantages by supporting parallelism, low cost in creating and destroying, and easy to manage. Be remember that main thread in a process can create several child threads.

In order to create Thread, Java gives you 2 options:

  • Extends Thread class
  • Implements Runnable interface

3 simple steps to create thread:

1) Extends Thread class or implements Runnable interface

public class MyThread extends Thread

or

public class MyRunnable implements Runnable

2) Override run method

public class MyThread extends Thread{
  public void run(){
    //To do your parallel work here
 }
}

or

public class MyRunnable implements Runnable{
  public void run(){
    //To do your parallel work here
  }
}

3) Call start() method to activate the thread

Thread thread1 = new MyThread();
thread1.start();

or

Thread thread2 = new Thread(new MyRunnable());
thread2.start();

The full example of creating 2 threads running in parallel is shown below:

  • MyThread.java : Thread implementation by extending Thread class
  • MyRunnable.java : Thread implementation by implementing Runnable interface
  • TestThreadRunnable.java : Test the two threads above

MyThread.java

public class MyThread extends Thread{
  private String _name;
  private String _str;
  public MyThread(String name, String str){
    _name = name;
    _str = str;
  }

  @Override
  public void run(){
    for(int i=0; i<5; i++){
      System.out.println(_name + " : " + _str);
      try{
        Thread.sleep(100);
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
    }
  }
}

MyRunnable.java

public class MyRunnable implements Runnable{
  private String _name;
  private String _str;

  public MyRunnable(String name, String str){
    _name = name;
    _str = str;
  }

  public void run(){
    for(int i=0; i<5; i++){
      System.out.println(_name + " : " + _str);
      try{
        Thread.sleep(100);
      }catch(InterruptedException ie){
        ie.printStackTrace();
      }
    }
  }
}

TestThreadRunnable.java

public class TestThreadRunnable {
  public static void main(String[] args){
    MyThread thread1 = new MyThread("Thread 1", "ping");
    Thread thread2 = new Thread(new MyRunnable("Thread 2", "pong"));

    //Starting thread
    thread1.start();
    thread2.start();
  }
}

Output:

Thread 1 : ping
Thread 2 : pong
Thread 1 : ping
Thread 2 : pong

My final comment:

When you have to run AA and BB concurrently, you need to implement AA in thread and BB in thread as well.

One response so far

Leave a Reply