Languages
[Edit]
EN

Java - create thread

4 points
Created by:
Tehya-Blanchard
444

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.");
        }
    }
}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java concurrency

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join