// // simple example of threads in Java, showing (possible) interleaving // of actions from two independent threads. whether/how they are // interleaved depends on the scheduler in use and so may be // different on different systems. // // see main method below for command-line arguments. // // // a PingPong object, when executed by a thread, repeatedly // prints message msg. // public class PingPong implements Runnable { String msg ; int cycles ; PingPong(String m, int c) { msg = m ; cycles = c ; } // implements run() in Runnable interface to define object's // behavior. public void run() { for (int i = 0 ; i < cycles ; i++) System.out.println(msg) ; } // command-line arguments are integers S1, S2, C. // builds and starts two threads using PingPong // 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 < 1) { System.out.println("Arguments are:") ; System.out.println(" cycles") ; System.exit(-1) ; } int C = Integer.parseInt(args[0]) ; Thread t1 = new Thread( new PingPong("ping---->", C)) ; Thread t2 = new Thread( new PingPong("<----pong", C)) ; t1.start() ; t2.start() ; } }