EN
Java - create thread
4 points
In this article, we would like to show how to create thread in Java.
Quick solution:
xxxxxxxxxx
1
Thread thread = new Thread(() -> {
2
// ...
3
// put your logic here ...
4
// ...
5
});
6
7
thread.start();
In the below source codes System.out.println("Executed in thread.")
is executed in thread that was created by programmer.
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
5
Thread thread = new Thread(() -> {
6
for (int i = 0; i < 3; ++i) {
7
System.out.println("Executed in thread.");
8
}
9
});
10
thread.start();
11
}
12
}
Output:
xxxxxxxxxx
1
Executed in thread.
2
Executed in thread.
3
Executed in thread.
xxxxxxxxxx
1
package com.example.demo;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
Thread thread = new Thread(new Runnable() {
8
9
public void run() {
10
for (int i = 0; i < 3; ++i) {
11
System.out.println("Executed in thread.");
12
}
13
}
14
});
15
thread.start();
16
}
17
}
Output:
xxxxxxxxxx
1
Executed in thread.
2
Executed in thread.
3
Executed in thread.
Program.java
file:
xxxxxxxxxx
1
package com.example.demo;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
Thread thread = new Thread(new SomeRunner());
8
thread.start();
9
}
10
}
Output:
xxxxxxxxxx
1
Executed in thread.
2
Executed in thread.
3
Executed in thread.
SomeRunner.java
file:
xxxxxxxxxx
1
package com.example.demo;
2
3
public class SomeRunner implements Runnable {
4
5
6
public void run() {
7
for (int i = 0; i < 3; ++i) {
8
System.out.println("Executed in thread.");
9
}
10
}
11
}