/** * A test of threads in Java. */ public class ThreadTest implements Runnable { public static void main(String[] args) throws InterruptedException { long tid = Thread.currentThread().getId(); System.out.println("Starting main thread, tid is " + tid); Thread[] threads = new Thread[5]; for (int i = 0; i < 5; i++) { Thread t = new Thread(new ThreadTest()); // create the Thread object threads[i] = t; t.start(); // start running the new thread concurrently } for (int i = 0; i < 5; i++) { threads[i].join(); // wait until threads[i] finishes } System.out.println("Exiting main thread"); } @Override public void run() { long tid = Thread.currentThread().getId(); System.out.println("Running thread, tid is " + tid); try { Thread.sleep(1000); // do some work ... } catch (InterruptedException e) {} System.out.println("Exiting thread, tid is " + tid); } }