A single program can have multiple subprocesses running in parallel. This is done through classes that extend Thread or that implement the Runnable interface. The class Thread provides the following methods (and more):
class PingPong extends Thread { String word; // what to print int delay; // how long to pause /* constructor */ PingPong(String word, int delay) { this.word = word; this.delay = delay; } public void run() { try { for (;;) { System.out.print(word + " "); sleep(delay); } } catch( InterruptedException e) { return; // end this thread } } public static void main(String[] args) { new PingPong("ping", 33).start(); new PingPong("pong", 100).start(); } }Alternative:
class PingPong implements Runnable { String word; // what to print int delay; // how long to pause /* same constructor */ /* same run() method but with Thread.sleep(delay), because we're not a Thread object */ public static void main(String[] args) { Runnable ping = new PingPong("ping", 33); Runnable pong = new PingPong("pong", 100); new Thread(ping).start(); new Thread(pong).start(); } }