Java 8 : Lambda with Thread Example

Hello Friends,
Thank you for visiting this blog. This is the continuation of my Java 8 video series tutorials which was published in youtube channel ekumeedhelp.

In this post, we will be learning about the use of Java 8 lambda expression in Thread.

Create Thread without using lambda 
Example:- 1

 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
//https://ekumeedkiasha.blogspot.com/
package com.blogspot.ekumeedkiasha;

public class Main {

public static void main(String[] args) {
Runnable r = new CodeToRun();
Thread t = new Thread(r);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main Thread i = " + i);
}
}
}

class CodeToRun implements Runnable {

@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("CodeToRun Thread i = " + i);
}

}

}


Create Thread with Lambda Example
Example:- 2


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//https://ekumeedkiasha.blogspot.com/
package com.blogspot.ekumeedkiasha;

public class Main {

public static void main(String[] args) {
Runnable r = () -> {
for (int i = 0; i < 10; i++) {
System.out.println("CodeToRun Thread i = " + i);
}
};

Thread t = new Thread(r);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main Thread i = " + i);
}
}
}




Create Thread using Anonymous class
Example:- 3

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//https://ekumeedkiasha.blogspot.com/
package com.blogspot.ekumeedkiasha;

public class Main {

public static void main(String[] args) {

Thread t = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("CodeToRun Thread i = " + i);
}
}
});
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main Thread i = " + i);
}
}
}

Share this

Related Posts

Previous
Next Post »

6 comments

Write comments
14 January 2020 at 09:27 delete

please add stream video also

Reply
avatar
28 April 2020 at 03:17 delete

clear and easy to learn. Great Job

Reply
avatar
23 May 2020 at 12:37 delete

can you please make sessions on spring microservices and cloud.

Reply
avatar