Skip to main content
Threads · Topic 2 of 7

Creating threads

Definition​

A thread is one path of execution. You create one by giving a Thread some code to run (a Runnable, usually a lambda) and calling start(). Call join() to wait until it has finished.

Example code​

Three threads each compute a result, and main waits for them

class Demo {
public static void main(String[] args) throws InterruptedException {
int[] results = new int[3];
Thread[] threads = new Thread[3];

for (int i = 0; i < threads.length; i++) {
int id = i;
threads[i] = new Thread(() -> results[id] = (id + 1) * 100, "worker-" + i); // the code to run
threads[i].start(); // run it in parallel
}

for (Thread thread : threads) thread.join(); // wait for all of them

System.out.println(java.util.Arrays.toString(results));
}
}

// Output:
// [100, 200, 300]

Finished this page? Track your progress (saved only in your browser).