Sunday 15 April 2012

Threading in Java

Every thread in Java needs a Runnable. To make a runnable, you must first create a class which implements the Runnable interface. Runnable interface has a method called run() which gets called by the Thread. Your class will need to have this method. Put your code in this run() method. Your Runnable class should look similar to:

public class Work implements Runnable{

    @Override
    public void run() {
        //do some work..
    }

}
Now, you can create a thread in multiple ways but the most appropriate way is to pass the runnable object in its constructor.

Thread thread1 = new Thread(new Work());
Work work = new Work();
Thread thread2 = new Thread(work);


thread1 and thread2 are both valid threads. Now to start a thread, just write:

thread1.start();
thread2.start();
Make sure that you say thread1.start() and not thread1.run(). thread1.run() simply calls the run method within the runnable while thread1.start() runs the run method in separate thread.

Thats it! Now you know the basics of threading in Java!

Watch the video tutorial here:

2 comments:

  1. You missed out the option to extend the thread class to create threads.

    ReplyDelete
    Replies
    1. Thats another way to do it. I personally prefer this way as it is much more flexible. :D

      Delete