一路线程交替读取的面试题
一道线程交替读取的面试题
有两个单词的txt文本a.txt和b.txt,a是以换行区分单词,b是 换行或者空格符。写一个程序,交替读取a和b文件中的单词保存在文件c中。
代码如下:
有两个单词的txt文本a.txt和b.txt,a是以换行区分单词,b是 换行或者空格符。写一个程序,交替读取a和b文件中的单词保存在文件c中。
代码如下:
package com.kaiying.face; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class FileWriteAndReadTest { private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private Condition otherCondition = lock.newCondition(); private OutputStream out; private boolean turnA = true;//读A false 读B文件 private boolean empty = false;//判断有一个文件的单词全部读完 public FileWriteAndReadTest() { try { out = new FileOutputStream("d.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } class ReadFileA implements Runnable { public void run() { try { lock.lock(); InputStream in = new FileInputStream("a.txt"); int r = 0; while ((r = in.read()) != -1) { while (!turnA) { otherCondition.await(); } writeByte(r); if (r == 10) {// 换行 if (!empty) { turnA = false; System.out.println("A"); condition.signal(); } } } turnA = false; empty = true; } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } class ReadFileB implements Runnable { public void run() { try { lock.lock(); InputStream in = new FileInputStream("b.txt"); int r = 0; while ((r = in.read()) != -1) { while (turnA) { condition.await(); } writeByte(r); if (r == 10 || r == 32) {// 换行 空格 if (!empty) { System.out.println("B"); turnA = true; otherCondition.signal(); } } } turnA = true; empty = true; } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public void writeByte(int byteWord) { try { out.write(byteWord); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { FileWriteAndReadTest test = new FileWriteAndReadTest(); ReadFileA fileA = test.new ReadFileA(); ReadFileB fileB = test.new ReadFileB(); new Thread(fileA).start(); new Thread(fileB).start(); } }