package J20250804.demo02;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;

/**
 * @author WanJl
 * @version 1.0
 * @title Consumer
 * @description
 * @create 2025/8/4
 */
public class Consumer implements Runnable{

    private String outputFile;
    private BlockingQueue<String> queue;
    //true 偶数，false为奇数
    private boolean isEvenConsumer;

    public Consumer(String outputFile, BlockingQueue<String> queue,boolean isEvenConsumer) {
        this.outputFile = outputFile;
        this.queue=queue;
        this.isEvenConsumer=isEvenConsumer;
    }
    @Override
    public void run() {
        BufferedWriter bw = null;
        try{
            bw=new BufferedWriter(new FileWriter(outputFile));
            while (!queue.isEmpty()){
                //从队列中获取数据，如果队列空了会阻塞等待
                String data = queue.take();
                try{
                    //把字符串转换为整数
                    int i = Integer.parseInt(data);
                    //根据消费者的类型判断是否处理当前的数字
                    if (isEvenConsumer&&i%2==0||!isEvenConsumer&&i%2!=0){
                        bw.write(data);
                        bw.newLine();
                    }
                }catch (NumberFormatException e){
                    System.out.println("忽略非数字数据："+data);
                }
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
