Java Thread Example: Runnable vs Thread

Today, i walk you through the Java Thread Example. Every java application has at least one thread or main thread. Multithreading refers to two or more threads executing concurrently in a single program. A computer single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different processes and threads.

Why we use Java Thread
a. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.
b. Threads share their parent process data and code
c. Context switching between threads is usually less expensive than between processes.
d. Thread intercommunication is relatively easy than process communication.

Java provides two ways to create a thread programmatically
1) Implementing Runnable interface.
To convert a class to runnable, you are able to implement java.lang.Runnable interface and do implementation in public void run() method.

2) Extending the java.lang.Thread class.
We can extend java.lang.Thread class to create our own java thread class and override run() method.

Here is a demo program that shows how to execute our java thread above

Output of the above java thread example program like this

java thread example

Runnable vs Thread
If a class only goal is to run as Thread, It should be extend from Thread class. Whereas, if a class provides more functiionality (e.g implementing multiple interfaces) rather than just running as Thread, it should be implemented Runnable interface.

Note: In Java 8, Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class above. The above code can be rewrite like this:

That’s all about Java Thread Example. Happy learning.

References
Processes and Threads

Download the complete source code, click link below

Sample.zip (17 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons