import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Threads21 {
	public static synchronized void main(String[] args) {
		File counterFile = new File ("counter");

		for (int threadCount=0; threadCount < Integer.parseInt(args[0]); threadCount++)
			(new IncrementCounter(counterFile)).start();
	} //main()
} //class Threads21

class IncrementCounter extends Thread {
	File	counterFile;
	public IncrementCounter(File rwFile) {
		counterFile = rwFile;
	} //constructor

	public void run() {
		int counterValue;
		DataInputStream dis = null;
		DataOutputStream dos = null;

		try {
			for (int i=0; i<10; i++) {
				synchronized (counterFile) {
					dis = new DataInputStream( new FileInputStream( counterFile ));
					counterValue = dis.readInt();
					dis.close();

					System.out.println(counterValue+" read by thread "+ (Thread.currentThread()).getName() );

					dos = new DataOutputStream( new FileOutputStream( counterFile ));
					dos.writeInt( ++counterValue );
					dos.close();
				}//synchronized
			} //for
		} catch (FileNotFoundException fnfe) {
			System.out.println("file counter could not be opened!\n"+fnfe.toString()+"\n"+fnfe.getMessage() );
			System.exit(1);
		} catch (IOException ioe) {
			System.out.println("an IOException occurred in thread "+(Thread.currentThread()).getName()+"!\n"+ioe.toString()+"\n"+ioe.getMessage() );
			System.exit(1);
		} //catch
	} //run()
} //class IncrementCounter	