import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

public class Threads2 {
	public static void main(String[] args) {
		for (int threadCount=0; threadCount < Integer.parseInt(args[0]); threadCount++)
			(new IncrementCounter()).start();
	} //main()
} //class Threads2

class IncrementCounter extends Thread {
	public void run() {
		int counterValue;
		DataInputStream dis = null;
		DataOutputStream dos = null;

		try {
			for (int i=0; i<10; i++) {
				dis = new DataInputStream( new FileInputStream( "counter" ) );
				counterValue = dis.readInt();
				dis.close();

				System.out.println(counterValue+" read by thread "+ (Thread.currentThread()).getName() );

				dos = new DataOutputStream( new FileOutputStream( "counter", false ) );
				dos.writeInt( ++counterValue );
				dos.close();
			} //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	