Tuesday 24 January 2012

How do I do threaded programming in Java?


My favorite concept in any programming language is Threading. It is awesome. This time, I'll get started straight away!

First of all, before making a thread in java, you need a runnable. Runnable is basically like a piece of code that you want to execute as a separate thread. There are two ways to create a runnable. You can do it by making an anonymous class such as:

Runnable r = new Runnable(){

public void run(){


//Your code goes here...


}
}
However, this is not a good practice. Hence, it is advised to create a separate class which implements the Runnable interface like:


public class MyNewRunnable implements Runnable{


MyNewRunnable(){


}


public void run(){
//Your code here...
}
}

In this manner, you can pass any parameters for processing the information using the class constructor. For instance, if you are making a runnable for downloading files, you can pass url of the file through the class constructor. Now, once you have created your runnable, you need a thread in which you have to put the runnable. Then you run the thread, the run method of runnable gets executed. For runnable r, you can make a thread as follows:

Thread t = new Thread(r);

Then, you can start the thread by typing:

t.start();

I'd say that threading would help make your program more responsive. This is solely because of the fact that all the heavy processor hungry tasks are carried out in a separate thread and the UI thread is kept clean.

See Also: How do I do threading in C#?

No comments:

Post a Comment