package waitnotify;

public class CoordinatedCountdown implements Runnable {

	private int value_;
	private String indent_;
	private Object coordinator_;

	public CoordinatedCountdown ( int value, String indent, Object coordinator ) {
		value_ = value;
		indent_ = indent;
		coordinator_ = coordinator;
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run () {
		for ( ; value_ >= 0 ; value_-- ) {
			System.out.println(indent_ + value_);
			try {
				Thread.sleep((long)(Math.random()*1000));
			} catch ( InterruptedException e ) {}
			
			if ( value_ % 5 == 0 ) {
				try {
					synchronized ( coordinator_ ) {
						coordinator_.wait();
					}
				} catch ( InterruptedException e ) {}
			}
		}
		System.out.println(indent_ + "done!");
	}

}
