importjava.io.*;classBuffer
{privatechar[] contents;privateintsize;privateintstate;publicfinalstaticintFULL=0;publicfinalstaticintEMPTY=1;publicfinalstaticintUNSTABLE=2;publicfinalstaticintEND=3;publicBuffer()
{
state=EMPTY;
}publicchar[] getContents()
{returncontents;
}publicvoidsetContents(char[] contents,intsize)
{this.contents=contents;this.size=size;
}publicintgetSize()
{returnsize;
}synchronizedpublicintgetState()
{returnstate;
}synchronizedpublicvoidsetState(intstate)
{this.state=state;
}
}classThread1extendsThread
{privateString inputFile;privateBuffer buffer;publicThread1(String inputFile)
{this.inputFile=inputFile;this.buffer=newBuffer();
}publicvoidrun()
{try{
BufferedReader in=newBufferedReader(newFileReader(newFile(
inputFile)));intsize=0;while(true)
{char[] contents=newchar[102];
size=in.read(contents,0,100);if(size<=0)break;synchronized(buffer)
{if(Buffer.EMPTY!=buffer.getState())
{
buffer.wait();
}
System.out.println("Thread1:"+size);
buffer.setContents(contents, size);
buffer.setState(Buffer.FULL);
buffer.notify();
}
}
buffer.setState(Buffer.END);synchronized(buffer)
{
buffer.notify();
}
in.close();
}catch(FileNotFoundException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}catch(IOException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}catch(InterruptedException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}publicBuffer getBuffer()
{returnbuffer;
}
}classThread2extendsThread
{privateString outputFile;privateBuffer buffer;publicThread2(String outputFile, Buffer buffer)
{this.outputFile=outputFile;this.buffer=buffer;
}publicvoidrun()
{try{
BufferedWriter out=newBufferedWriter(newFileWriter(newFile(outputFile)));while(true)
{synchronized(buffer)
{intstate;while(Buffer.FULL!=(state=buffer.getState()))
{if(Buffer.END==state)break;
buffer.wait();
}if(Buffer.END==state)break;
System.out.println("Thread2:"+buffer.getSize());
out.append(newString(buffer.getContents(),0, buffer.getSize()));
buffer.setState(Buffer.EMPTY);
buffer.notify();
}
}
out.close();
}catch(IOException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}catch(InterruptedException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}publicclassFileCopy
{publicstaticvoidmain(String[] argv)
{
Thread1 thread1=newThread1("f:\\1.txt");
Thread2 thread2=newThread2("f:\\2.txt", thread1.getBuffer());
thread1.start();
thread2.start();
}
}