package pbt.iotest;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * Illustration du pipe .. .avec un thread écrivain et un thread lecteur.
 * 
 * Remarque: Les notions de multithreading ne sont pas abordées en première. 
 * 
 * @author pbt
 */
public class PipedReaderWriter {
	static PipedReader reader;
	static PipedWriter writer;

	public static void main(String[] args) {
		ThreadÉcrivain tÉcrivain;
		ThreadLecteur tLecteur;
		
		try {
			reader = new PipedReader();
			writer = new PipedWriter(reader);
		} catch (IOException ioe) {
			System.err.println("Erreur d'E/S");
			System.exit(1);
		}
		tÉcrivain = new ThreadÉcrivain();
		tÉcrivain.run();
		tLecteur = new ThreadLecteur();
		tLecteur.run();
		try {
			tÉcrivain.join();
			tLecteur.join();
		} catch (InterruptedException ie) {
			System.err.println("Thread erreur");
		}

	}


 

	
	/** 
	 * Classe interne héritant de la classe Thread. 
	 * ThreadÉcrivain écrit dans le thread. 
	 */
	public static class ThreadÉcrivain extends Thread {
		public ThreadÉcrivain() {
			super();
		}

		/** méthode principale du thread */
		public void run() {
			System.out.println("Écrivain: J'écris ... ");
			try {
				writer.write("Hello world");
				writer.close();
			} catch (IOException ioe) {
				System.err.println("Erreur d'E/S");
				System.exit(1);
			}
			System.out.println("Écrivain: fin");
		}
	}// end ThreadÉcrivain







	/**
	 * Ce thread se charge de lire dans le pipe.
	 */
	public static class ThreadLecteur extends Thread {
		public ThreadLecteur() {
			super() ; 
		}

		/** méthode principale du thread */
		public void run() {
			int b ; 
			System.out.println("Lecteur: Je lis ... ");
			try {
				while ( (b=reader.read()) != -1 )
					System.out.println((char)b);
			} catch ( IOException ioe ) {
				System.err.println("Erreur d'E/S");
				System.exit(1) ; 
			}
			System.out.println("Lecteur: fin");
 		}
	}
}
