/* CS 1520 Summer 2011 Java Example 2 Simple introduction to using threads. This program shows the basics of using threads in Java. In this case the Thread class is extended and each thread object "runs on itself". */ import javax.swing.*; class MyThread extends Thread // extending the Thread class { int id; // id number for thread int outputs; // how many prints to do public MyThread(int id, int iter) { this.id = id; // simple constructor to give object its id and this.outputs = iter; // number of iterations } public void run() // This method will be implicitly called when the { // thread is started. run() is the sole method // required for the Runnable interface, which Threads // implement. We override it in our own Thread classes // to have the Thread "run" the way we want it to. int i = 1; while (i <= outputs) // iterate outputs times { System.out.println("Thread " + id + " iterating for " + i + "th out of " + outputs + " times"); try { Thread.sleep(500); } catch (InterruptedException e) // when a Thread calls the static // method sleep(), it is required // to catch (or pass on with a throws clause) the // exception shown above (it is a checked exception) { System.out.println("Hey, who woke me? "); } i++; } // The code below demonstrates how threads are switched in and out of // the running state for (int j = 1; j <= 160; j++) { System.out.print(id); if (j % 80 == 0) System.out.println(); } // The run() method begins executing when the start() method of a Thread // is called. The Thread will continue to "run" until either the run() // method completes or it is abnormally terminated (ex. due to an // exception). However, due to scheduling and shared data access // concerns, a Thread may not always be actively "running". } } public class ex2 { static int getNumThreads() // Get number of Threads (with error checking) { int val = 0; while (true) { try { val = Integer.parseInt( JOptionPane.showInputDialog("How many threads?")); break; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null,"Not an integer!"); } } return val; } public static void main(String [] argv) { int num_threads; num_threads = getNumThreads(); System.out.println("There will be " + num_threads + " threads"); MyThread [] T = new MyThread[num_threads]; // array of MyThread // created, but no actual MyThreads exist yet // (since it is an array of references) for (int i = 0; i < T.length; i++) { T[i] = new MyThread(i, 3); // Creating a new MyThread object T[i].start(); // Starting it running } System.out.println("Main is done"); // Note when this message appears } }