public class ThreadExample1 { Object obj; static int i; public ThreadExample1() { this.obj = new Object(); this.i = 0; } class Ith implements Runnable { volatile boolean running; int myi; public Ith() { this.running = true; this.myi = i++; } public void run() { while(true) { System.out.println("Thread " + myi + " running"); while(running) { //task } System.out.println("Thread " + myi + " stopped"); try { synchronized(obj) { obj.wait(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void execute() { Ith[] threads = {new Ith(), new Ith(), new Ith(), new Ith(), new Ith()}; for(Runnable r: threads) { new Thread(r).start(); } while(true) { //stop threads for(Ith r: threads) { r.running = false; } //sleep 5 seconds try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //restart threads for(Ith r: threads) { r.running = true; } synchronized(obj) { obj.notifyAll(); } System.out.println("All threads running\n\n"); //sleep 5 seconds try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { new ThreadExample1().execute(); } }