日期:2014-05-20  浏览次数:20770 次

求高手解决线程和io流问题(急!!!!!)
生产者从输入文件source.txt中读取字符串(一串数字如:45,54,2,8,65,99,354,5)信息并放入缓冲区,消费者从缓冲区中获取信息字符串输出到结果输出文件result.txt中
要求:生产者线程从文件中读取字符串数字并存入缓冲区,缓冲区(Buffer)中允许的最大数字数为5个
io?Thread

------解决方案--------------------
抽时间写了一个,看看吧,理解一下。

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{