Simple threads in Java
In Java, a thread is a separate path of execution within a program. A java application always starts with the main-thread
.
There are two most common ways to create simple threads in java
- By extending
java.lang.Thread
class or - By implementing
java.lang.Runnable
interface
In both cases, we have to provide the code block which will be executed in run
method. These statements are executed on a separate path other than main-thread
. Thread class itself internally implements Runnable interface.
By extending Thread class
1class ThreadSubClass extends Thread {
2 public ThreadSubClass(String name) {
3 super(name);
4 }
5
6 @Override
7 public void run() {
8 String output = String.format("Thread code running on %s", Thread.currentThread().getName());
9 System.out.println(output);
10 }
11}
By implementing Runnable interface
1class RunnableClass implements Runnable {
2
3 @Override
4 public void run() {
5 String output = String.format("Runnable code running on %s", Thread.currentThread().getName());
6 System.out.println(output);
7 }
8}
Program
1public class SimpleThreadInJava {
2
3 public static void main(String[] args) {
4 System.out.printf("Current Application Thread - %s%n", Thread.currentThread().getName());
5 Thread thread1 = new ThreadSubClass("CustomThreadExtended-0");
6 Thread thread2 = new Thread(new RunnableClass(), "Runnable-0");
7 thread1.start();
8 thread2.start();
9 }
10}
Output
1Current Application Thread - main
2Thread code running on CustomThreadExtended-0
3Runnable code running on Runnable-0
Creating thread is costly, always be careful when creating
new Thread()
inside loops.
Ref
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
comments powered by Disqus