Concurrency Basics
Starting and Joining Threads
Java Thread objects run Runnable work on separate threads. The trace records
which thread produced each event, and replay uses color to show the active
thread inside the same source pane.
Worker Threads
StartJoin.java
public class StartJoin {
static class Worker implements Runnable {
private final String name;
private final int limit;
Worker(String name, int limit) {
this.name = name;
this.limit = limit;
}
@Override
public void run() {
for (int step = 1; step <= limit; step++) {
String message = name + ":" + step;
System.out.println(message);
}
}
}
public static void main(String[] args) throws InterruptedException {
int limit = ;
Thread alpha = new Thread(new Worker("alpha", limit));
Thread beta = new Thread(new Worker("beta", limit));
alpha.start();
beta.start();
alpha.join();
beta.join();
System.out.println("done");
}
}
public class StartJoin {
static class Worker implements Runnable {
private final String name;
private final int limit;
Worker(String name, int limit) {
this.name = name;
this.limit = limit;
}
@Override
public void run() {
for (int step = 1; step <= limit; step++) {
String message = name + ":" + step;
System.out.println(message);
}
}
}
public static void main(String[] args) throws InterruptedException {
int limit = ;
Thread alpha = new Thread(new Worker("alpha", limit));
Thread beta = new Thread(new Worker("beta", limit));
alpha.start();
beta.start();
alpha.join();
beta.join();
System.out.println("done");
}
}
start
`start()` asks the JVM to run the task on a new thread instead of calling `run()` on the current thread.
join
`join()` waits until a thread has finished before the main thread continues.