EN
Java - create thread
4
points
In this article, we would like to show how to create thread in Java.
Quick solution:
Thread thread = new Thread(() -> {
// ...
// put your logic here ...
// ...
});
thread.start();
Practical example
In the below source codes System.out.println("Executed in thread.")
is executed in thread that was created by programmer.
1. Using lambda expression
public class Program {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 3; ++i) {
System.out.println("Executed in thread.");
}
});
thread.start();
}
}
Output:
Executed in thread.
Executed in thread.
Executed in thread.
2. Using anonymous class
package com.example.demo;
public class Program {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; ++i) {
System.out.println("Executed in thread.");
}
}
});
thread.start();
}
}
Output:
Executed in thread.
Executed in thread.
Executed in thread.
3. Using separated class
Program.java
file:
package com.example.demo;
public class Program {
public static void main(String[] args) {
Thread thread = new Thread(new SomeRunner());
thread.start();
}
}
Output:
Executed in thread.
Executed in thread.
Executed in thread.
SomeRunner.java
file:
package com.example.demo;
public class SomeRunner implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; ++i) {
System.out.println("Executed in thread.");
}
}
}