public class BasicThreads {
// This top-level nested class implements Runnable, because when
// you construct a Thread object it will expect to get an object
// which promises to be runnable, i.e., that has a "run" method
//
private static class Printer implements Runnable {
private String name;
Printer(String name) {
this.name = name;
}
public void run() { // must implement "run"
for(int i = 0; i < 10; i++) { // print 0 -- 9
System.out.println(name + ": " + i); // prefix output with name
}
}
}
public static void main(String[] args) {
// Create two threads that run Printers with different names
Thread t1 = new Thread(new Printer("a"));
Thread t2 = new Thread(new Printer("b"));
// Start both threads
t1.start();
t2.start();
// Wait for both threads to finish
try {
t1.join();
t2.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("Done");
}
}