交替输出

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.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

//编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final BlockingQueue<String> queue=new ArrayBlockingQueue<>(100);
		final Read read1=new Read();
		read1.queue=queue;
		read1.myflag=1;
		final Read read2=new Read();
		read2.queue=queue;
		read2.myflag=2;
		read1.opp=read2;
		read2.opp=read1;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					read1.read(new File("G:\\iotest\\a.txt"));
				} catch(Exception e){
					e.printStackTrace();
				}
				
			}
		},"r1").start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					read2.read(new File("G:\\iotest\\b.txt"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		},"r2").start();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				FileWriter fw = null;
				try {
					fw = new FileWriter(new File("G:\\iotest\\c.txt"));				
					BufferedWriter bw=new BufferedWriter(fw);
					while(true){
						String str = null;					
						str = queue.take();						
						if("##".equals(str)){						
								bw.close();
								fw.close();							
							return;
						}						
						bw.append(str);						
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
		},"write").start();
		
		
		
	}

}
class Read{
	int myflag;
	static int flag=1;
	BlockingQueue<String> queue;
	static Object lock=new Object();
	boolean finsh=false;
	Read opp;
	public void read(File file) throws IOException, InterruptedException{
		FileReader fr=new FileReader(file);
		BufferedReader br=new BufferedReader(fr);
		String str=null;
		synchronized (lock) {
			while((str=br.readLine())!=null){
				String[] s=str.split(" ");
				for(int i=0;i<s.length;++i){
						while(flag!=myflag&&!opp.finsh)
							lock.wait();
						queue.put(s[i]);
						flag=flag==1?2:1;
						lock.notify();
						
				}													
			}
			finsh=true;
			if(opp.finsh){
				queue.put("##");
			}
			try{
				lock.notify();
			}catch(Exception e ){
					
			}
			
		}
		
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值