/** Thread that prints out the elements of the sequence seed, seed+2, seed+4, .. and sleeps a random time in between each element. It continues until interrupted. */ class Child extends Thread { private int seed; public Child(int seed) { this.seed = seed; } public void run() { for (int k = seed; ; k += 2) { System.out.println(k); try { sleep((long)(1000*seed*Math.random())); } catch (InterruptedException e) { System.out.println("Interrupted sleep " + seed); break; } } } } /** It starts two Child threads with different seeds and after a while terminates them by sending interrupts */ public class Thread1 { public static void main(String[] args) { Thread child1 = new Child(1); child1.start(); Thread child2 = new Child(2); child2.start(); try { Thread.sleep(10000); // sleep 10 seconds child1.interrupt(); child2.interrupt(); child1.join(); child2.join(); } catch (InterruptedException e) { System.out.println("Interrupted main"); } System.out.println("Main is done"); } }