<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">public class RunPingPong implements Runnable {
    
    private static final int numberOfPings = 4;
    private static final int numberOfPongs = 4;
    private static int nextID = 0;

    private String word;  // what word to print
    private int delay;    // how long to pause (milliseconds)
    private int reps;     // number of times to repeat word
    private int id;       // unique object identifier
    
    private RunPingPong(String whatToSay, int delayTime, int repeatTimes) {
	word = whatToSay;
	delay = delayTime;
	reps = repeatTimes;
	id = nextID++;
    }

    public synchronized void run() {
	try {
	    for (int t = 0; t &lt; reps; ++t) {
		System.out.print(word + "[" + id + "] ");
		wait(delay);  // wait for the required time or until notified
	    }
	} catch (InterruptedException e) {
	    System.out.print("[" + id + "]-interrupted! ");
	} finally {
	    System.out.print("[" + id + "]-finished! ");
	}
    }

    public static void main(String[] args) {
	Thread[] PingPongThreads = new Thread[numberOfPings + numberOfPongs];
	Object Notifier = new Object();  // synchronization Object
	
	for (int i = 0; i &lt; numberOfPings; ++i) {
	    (PingPongThreads[i] = new Thread(new RunPingPong("ping", 33, 2*i+1))).start();
	}
	for (int i = numberOfPings; i &lt;  PingPongThreads.length; ++i) {
	    (PingPongThreads[i] = new Thread(new RunPingPong("PONG", 100, i+1))).start();
	}
	
	try {
	    for (int i = 0; i &lt; PingPongThreads.length; i += 3) {
		Thread.sleep(50);
		if (PingPongThreads[i].isAlive()) {
		    PingPongThreads[i].interrupt();
		}
		synchronized (Notifier) {
		    Notifier.notify();  // wait and notify must occur within synchronized code
		}
	    }   
	    for (int i = 0; i &lt; PingPongThreads.length; ++i) {
		PingPongThreads[i].join();
	    }
	} catch (InterruptedException e) {
	    System.exit(0);
	} finally {
	    System.out.print("Done!");
	}
    }
}
</pre></body></html>