How to create a thread



Execution in Java always take form of a thread. In simple programs only one thread occurs, often referred to as the ‘main thread’.
In some programs though concurrent threads are necessary, or if you are building a Swing application with for example a progress bar you don’t want the main thread to handle the updates of the UI.
Instead you create an additional thread to take care of that. There are two main ways of creating a thread. The first is to extend the Thread class and the second is to implement the Runnable interface.

If you’re using a Java version >= 8, you might want to read this as well:
How to create threads using lambda expressions

So when should we extend the Thread class and when should we implement the Runnable interface?

The Thread class should be extended when you plan to write more code in that class except for the code in the run() method. If you’re only going to put code in the run() method, always use the implement Runnable approach. This is because a class should not be extended if you’re not planning to modify its fundamental behaviour.

Extending Thread:

Implementing the Runnable interface:







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">