// // simple example of threads in Java, showing interleaving of actions // from two independent threads // // in this version, thread objects are created using a class that // implements the Runnable interface (compare with // SimpleThread.java, which behaves the same but is implemented // slightly differently). // // see main method below for command-line arguments. // // // a SimpleThreadObj object, when executed by a thread, repeatedly // prints message msg and then sleeps for sleepIntvl milliseconds. // public class SimpleThreadObj implements Runnable { String msg ; long sleepIntvl ; int cycles ; SimpleThreadObj(String m, int s, int c) { msg = m ; sleepIntvl = (long) s ; cycles = c ; } // implements run() in Runnable interface to define object's // behavior. public void run() { try { for (int i = 0 ; i < cycles ; i++) { System.out.println(msg) ; Thread.sleep(sleepIntvl) ; // note this change } // 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 using SimpleThreadObj // objects, 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]) ; Thread t1 = new Thread( new SimpleThreadObj("ping---->", S1, C)) ; Thread t2 = new Thread( new SimpleThreadObj("<----pong", S2, C)) ; t1.start() ; t2.start() ; } }