Use Thread.ofPlatform() to create a platform thread. Pass it a Runnable that describes the work, then call start() to run that work on the new thread.
In this example, a worker thread prints its name, and the main thread waits for it to finish.
Source code
Save the following code as ThreadExample.java:
public class ThreadExample {
void main() throws InterruptedException {
Runnable task = () -> {
String threadName = Thread.currentThread().getName();
IO.println("Task running on: " + threadName);
};
Thread worker = Thread.ofPlatform()
.name("worker")
.unstarted(task);
IO.println("Starting the worker.");
worker.start();
worker.join();
IO.println("The worker has finished.");
}
}
Explanation
The Runnable describes what the worker should do. Here, a lambda calls Thread.currentThread() to get the thread that is executing the task, then prints its name.
Thread.ofPlatform() returns a thread builder. The name("worker") call sets the thread’s name, and unstarted(task) creates the thread without running the task yet.
The call to worker.start() schedules the task to run on the new thread. If you call task.run() directly, the task runs on the current thread instead.
Waiting for the worker
worker.join() waits until the worker finishes. This ensures that the final message appears after the task’s message. Without join(), the main thread could print its final message before the worker prints anything.
The join() method can throw InterruptedException if the main thread is interrupted while waiting. This example declares that exception in main().
Run the example
Compile and run the file:
javac ThreadExample.java
java ThreadExample
Output
Starting the worker.
Task running on: worker
The worker has finished.
A Thread can be started only once. To run the same task again on a new thread, create another Thread using the same Runnable.
