Wednesday, July 28, 2010

What is a Java Thread and How to create them ?

Threads are lightweight processes that appear to run in parallel with your main program. Unlike a process a thread shares memory and data with the rest of the program. The word thread is a contraction of "thread of execution".An example of where threads can be useful is in printing. When you click on a print button you probably don't want the main program to stop responding until printing has finished. What would be nice is that the printing process started running "in the background" and allowed you to continue using the main portion of the program.

There are 2 ways to create a java thread.
1. By extending the class with the Thread class.
2. By implementing the Runnable interface.

In both the cases we have to implement run() method.

The best way to create the thread is to implement Runnable interface. Because, As you know java will not support multiple inheritance so, if we extend the class with the Thread class we cant extend with any other class. If we implement the class with Runnable interface, we can extend any other class

No comments:

Post a Comment