package counters;

import java.awt.*;
import java.awt.event.*;

public class SynchronizedThreadCounters1 extends Frame {
	
	private Label counterA = new Label("counter A");
	private Label counter1Display = new Label  ("0");
	private Label counterB = new Label("counter B");
	private Label counter2Display = new Label  ("0");
	private Label syncLabel = new Label("unsynchronized");
	private Label unsyncDisplay   = new Label  ("0");
	private Button on            = new Button ("On");
	private Button off           = new Button ("Off");
	private int counter1;
	private int counter2;
	private int unsync;
	
	private	boolean active;
	
	public SynchronizedThreadCounters1() {
		counter1 = 0;
		counter2 = 0;
		unsync   = 0;
		active  = false;
		setLayout (new FlowLayout ());
		
		add(counterA);
		add(counter1Display);
		add(counterB);
		add(counter2Display);
		add(syncLabel);
		add(unsyncDisplay);
		add(on);
		add(off);
		
		addWindowListener(new WindowAdapter() {
					public void windowClosing(WindowEvent e) {
						System.exit(0);
					}
				});
		
		on.addActionListener (new ActionListener () {
					public void actionPerformed (ActionEvent e) {
						if (! active) {
							active = true;
							new Thread(new CountingTask()).start();
							new Thread(new SynchronizedCheckingTask()).start();
						}
					}
				});
		
		off.addActionListener (new ActionListener () {
					public void actionPerformed (ActionEvent e) {
						active = false;
					}
				});
		pack();
	}
	
	private boolean countersEqual(){
		return counter1 == counter2;
	}
	
	class CountingTask implements Runnable{
		public void run () {
			while (active) {
				try	{
					Thread.sleep(100);
				}
				catch (InterruptedException ie) {}
				
				counter1Display.setText(Integer.toString(counter1++));
				counter2Display.setText(Integer.toString(counter2++));
				
			}
		}
	}
	
	class SynchronizedCheckingTask implements Runnable {
		public void run (){
			while (active){
				if (! countersEqual()) {
					unsyncDisplay.setText(Integer.toString(unsync++));
				}
			}
		}
	}
	
	
	public static void main (String[] args){
		SynchronizedThreadCounters1 counter = new SynchronizedThreadCounters1();
		counter.setVisible(true);
	}
}
