日期:2014-05-20 浏览次数:20817 次
package com.study.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class T {
public static void main(String[] args) throws Exception {
Share share = new Share();
File in = new File("D:\\1\\resource.txt");
File out = new File("D:\\1\\result.txt");
Reader reader = new Reader(share, in);
Writer writer = new Writer(share, out);
reader.start();
writer.start();
}
}
class Share{
private List<String> contents = new ArrayList<String>(5);
private boolean isEnd = false;
public boolean isEnd() {
return isEnd;
}
public void setEnd(boolean isEnd) {
this.isEnd = isEnd;
}
public synchronized String get() {
while (!isEnd && contents.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
String line = null;
synchronized(contents){
if(contents.size() == 0){
return null;
}
line = contents.remove(0);
}
notifyAll();
return line;
}
public synchronized void put(String value) {
while (contents.size() >= 5) {
try {
wait();
} catch (InterruptedException e) {
}
}
notifyAll();
contents.add(value);
}
}
class Reader extends Thread{
private Share shared;
private File file;
public Reader(Share shared, File file){
this.shared = shared;
this.file = file;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void run(){
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while(true){
String line = reader.readLine();
if(line == null){
shared.setEnd(true);
break;
}
System.out.println("read line : " + line);
shared.put(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class Writer extends Thread{