// // simple example of threads in Java, showing interleaving of actions // from two independent threads // // in this version, thread objects are created using a subclass of // the Thread class (compare with SimpleThreadObj.java, which // behaves the same but is implemented slightly differently). // // see main method below for command-line arguments. // // // a SimpleThread object repeatedly prints message msg and then // sleeps for sleepIntvl milliseconds. // public class SimpleThread extends Thread { String msg ; long sleepIntvl ; int cycles ; SimpleThread(String m, int s, int c) { msg = m ; sleepIntvl = (long) s ; cycles = c ; } // overrides run() in Thread class to define object's // behavior. public void run() { try { for (int i = 0 ; i < cycles ; i++) { System.out.println(msg) ; sleep(sleepIntvl) ; } // can safely ignore interrupts here -- should not // happen in this program } catch (InterruptedException e) { } } // command-line arguments are integers S1, S2, C. // builds and starts two threads of type SimpleThread, with // sleep intervals of S1 and S2. observe the difference // in execution behavior when S1 and S2 are the same and // when they are different. // continues for C cycles. public static void main(String[] args) { if (args.length < 3) { System.out.println("Arguments are:") ; System.out.println(" sleep interval for t1") ; System.out.println(" sleep interval for t2") ; System.out.println(" cycles") ; System.exit(-1) ; } int S1 = Integer.parseInt(args[0]) ; int S2 = Integer.parseInt(args[1]) ; int C = Integer.parseInt(args[2]) ; SimpleThread t1 = new SimpleThread("ping---->", S1, C) ; SimpleThread t2 = new SimpleThread("<----pong", S2, C) ; t1.start() ; t2.start() ; } }