// // Very simple program demonstrating the use of threads. // // Command-line argument is P (number of threads). // // Synchronization via class (static) method. // // ---- class containing main program -------------------------------- public class ThreadsHello2 { public static void main(String[] args) { if (args.length < 1) { System.err.println("Usage: java ThreadsHello2 numThreads"); System.exit(1); } int P = Integer.parseInt(args[0]); Thread [] threads = new Thread[P]; // Create threads. for (int i = 0; i < P; ++i) threads[i] = new Thread(new Hello2Thread(i)); // Start them up. for (int i = 0; i < P; ++i) threads[i].start(); // Wait for them to finish. try { for (int i = 0; i < P; ++i) threads[i].join(); } catch (InterruptedException e) { // should never happen } System.out.println("That's all, folks!"); } } // ---- class for threads -------------------------------------------- // We'll have one object of this class for each thread. // It holds the data needed by the thread, plus the code. class Hello2Thread implements Runnable { // Instance variable (like C++ member variable). private int myID; // Constructor. public Hello2Thread(int myID) { this.myID = myID; } // Class method (like C++ static member function). private static synchronized void printMsg(int ID) { System.out.print("hello, world, "); System.out.println("from thread " + ID); } // Instance method (like C++ member function). // This one implements run() in Runnable interface to define // behavior of thread using this object. public void run() { printMsg(myID); } }