// // simple example of threads in Java, showing interleaving of actions // from two threads synchronizing on a shared object // // see main method below for command-line arguments. // // // a SharedObj object gives us a way to ensure that at most one // thread at a time is executing its repeatPrint() method. // class SharedObj { int reps ; SharedObj(int r) { reps = r ; } // prints msg and then sleeps sleepIntvl milliseconds, // reps times synchronized void repeatPrint(String msg, long sleepIntvl) throws InterruptedException { for (int i = 0 ; i < reps ; i++) { System.out.println(msg) ; Thread.sleep(sleepIntvl) ; } } } // // a SharingThread object repeatedly calls synchronized method // repeatPrint() to repeatedly print msg and sleep sleepIntvl // milliseconds. // public class SharingThread extends Thread { String msg ; long sleepIntvl ; int cycles ; SharedObj obj ; SharingThread(String m, int s, int c, SharedObj o) { msg = m ; sleepIntvl = (long) s ; cycles = c ; obj = o ; } // overrides run() in Thread class to define object's // behavior. public void run() { try { for (int i = 0 ; i < cycles ; i++) { obj.repeatPrint(msg, sleepIntvl) ; } // can safely ignore interrupts here -- should not // happen in this program } catch (InterruptedException e) { } } // command-line arguments are integers S1, S2, R, C. // builds and starts two threads of type SharingThread, with // sleep intervals of S1 and S2 (millisecs). the threads // share access a common SharedObj object with a // synchronized method to repeat the (print msg, sleep // S1 (S2) milliseconds) cycle R times. the effect is that // each thread is allowed to produce R messages at a time // (without interruption by the other thread). compare // with // SimpleThreads.java. // continues for C cycles. public static void main(String[] args) { if (args.length < 4) { System.out.println("Arguments are:") ; System.out.println(" sleep interval for t1") ; System.out.println(" sleep interval for t2") ; System.out.println(" messages per cycle") ; System.out.println(" cycles") ; System.exit(-1) ; } int S1 = Integer.parseInt(args[0]) ; int S2 = Integer.parseInt(args[1]) ; int R = Integer.parseInt(args[2]) ; int C = Integer.parseInt(args[3]) ; SharedObj o = new SharedObj(R) ; SharingThread t1 = new SharingThread("ping---->", S1, C, o) ; SharingThread t2 = new SharingThread("<----pong", S2, C, o) ; t1.start() ; t2.start() ; } }