Creating Threads in Java

This is First Article in Series of Articles on Java 8 Concurrency Tutorial.

Threads can be Created using below ways.

Extending Thread class

The First way is to extend the Thread class, and override the run()
The extending class must override run() method which is the entry point of new thread.

Extending Thread class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class ThreadRunner extends Thread
{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("ThreadRunner : " + i);
}
}

}

public class CreatingThreadsExample {

public static void main(String[] args) {

System.out.println("Main Method Start");

Thread t1= new ThreadRunner();
t1.start();
System.out.println("Main Method End");

}

}

Implementing the Runnable Interface

We Can pass an implementation of the Runnable interface to the constructor of Thread, then call start()

Implementing the Runnable Interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

class ThreadRunner implements Runnable
{
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("ThreadRunner1 : " + i);
}
}

}

public class CreatingThreadsExample {

public static void main(String[] args) {

System.out.println("Main Method Start");

Thread t1= new Thread(new ThreadRunner());
t1.start();
System.out.println("Main Method End");

}

}

Threads Using Anonymous Classes

Anonymous Inner class is an inner class that is declared without any class name and that’s why it’s called anonymous. You can define an anonymous inner class within a method or even within an argument to a method.

Anonymous class can be used to -
Extend an class and override its method.
Implement an interface and provide an implementation of its method.

Threads Using Anonymous Classes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CreatingThreadsExample {

public static void main(String[] args) {

System.out.println("Main Method Start");

new Thread(new Runnable() {

public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("ThreadRunner : " + i);
}

}
}).start();
}
}

Threads Using Java 8 Lambda

Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class.

Threads Using Anonymous Classes
1
2
3
4
5
6
7
8
9
10
public class CreatingThreadsExample {

public static void main(String[] args) {
Runnable task = () -> {
for (int i = 0; i < 100; i++) {
System.out.println("ThreadRunner2 : " + i);
} };
new Thread(task).start();
}
}

Next Join Method. in Series of Articles on Java 8 Concurrency Tutorial.

Share Comments