Sunday, January 29, 2012

Creating Threads in Java

In Java, you can create a thread in two ways by:

1.Extending the Thread class

This is the easiest way to create a new thread. You simply need to create a new class which should inherit the Thread class from the java.lang package.

The Thread class implements the interface Runnable which contains the method void run(). The method void run() should contain all the actions and logic that your thread needs to perform.
public class MyThread extends Thread
{
 private int iterations;
 private long sleepTime;
 public MyThread(String s, int iterations, long sleepTime)
 {
  super(s);
  this.iterations = iterations;
  this.sleepTime = sleepTime;
 }
 public void run()
 {
  for(int i=0;i<iterations;i++)
  {
   System.out.println("Hi! My name is " 
         + this.getName() 
         + "! Iteration " + i);
   try
   {
    Thread.sleep(sleepTime);
   }catch(InterruptedException ex){}
  }     
 }
}
The class above takes as arguments the thread's name (which is transmitted to the superclass Thread), the number of iterations (practically how many times it will print a message) and a time in milliseconds which represents for how long the thread is going to wait after printing a message before starting another iteration.

As you probably already observed, the static void sleep(long timeInMilliseconds) method is called inside a try/catch block. The call must be done in this fashion because the sleep function throws an InterruptedException if the thread is interrupted by another thread.

You can create several threads of the type MyThread. Here's an example:
MyThread t1 = new MyThread("Slim",3,500);
MyThread t2 = new MyThread("Shady",2,250);
t1.start();
t2.start();
//Output
//Hi! My name is Slim! Iteration 0
//Hi! My name is Shady! Iteration 0
//Hi! My name is Shady! Iteration 1
//Hi! My name is Slim! Iteration 1
//Hi! My name is Slim! Iteration 2
It is very important to observe that a thread is started by calling the void start() method, NOT the void run() method which we implemented before.

2.Implementing the Runnable Interface

There are some cases where you may want your thread to inherit a specific object who doesn't inherit the Thread class. Since Java doesn't allow multiple inheritance you will not be able to inherit the object's class and the Thread class.
This problem can be solved by creating a subclass of your "specific object" that will also implement the Runnable interface.
Let us suppose that you have a class called CounterContext with the following implementation:
public class CounterContext 
{
 private int iterations;
 private long sleepTime;
 private String name;
 
 public CounterContext (String name, int iterations, 
         long sleepTime)
 {
  this.name = name;
  this.iterations = iterations;
  this.sleepTime = sleepTime;
 }
 
 public int getIterations(){return iterations;}
 public long getSleepTime(){return sleepTime;}
 public String getName(){return name;}
}
The subclass who will inherit CounterContext will implement the Runnable interface.
public class MyNewThread extends CounterContext implements Runnable
{
 public MyNewThread(String name, int iterations, long sleepTime)
 {
  super(name,iterations,sleepTime);
 }
 
 public void run() 
 {
  int iterations = getIterations();
  long sleepTime = getSleepTime();
  for(int i=0;i<iterations;i++)
  {
   System.out.println("Hi! My name is " 
         + this.getName() 
         + "! Itteration " + i);
   try
   {
    Thread.sleep(sleepTime);
   }catch(InterruptedException ex){}
  }  
 }
}
The MyNewThread does exactly the same thing as MyThread, except that MyNewThread will not be able to run as a thread by itself, but can serve as a constructor argument for a Thread object. The newly created Thread object will behave exactly like a MyThread object (since the void run() methods are almost identical for both MyNewThread and MyThread).
Thread t1 = new Thread(new MyNewThread("Slim",3,500));
Thread t2 = new Thread(new MyNewThread("Shady",2,250));
t1.start();
t2.start();
//Output
//Hi! My name is Slim! Itteration 0
//Hi! My name is Shady! Itteration 0
//Hi! My name is Shady! Itteration 1
//Hi! My name is Slim! Itteration 1
//Hi! My name is Slim! Itteration 2

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger