使用CountDownLatch模拟多线程写文件,所有写文件线程写完后,主线程读取文件

使用CountDownLatch模拟多线程写文件,所有写文件线程写完后,主线程读取文件

package juc;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WriteFileTest {
    public static class WriteFileTask implements Runnable {
        private final CountDownLatch latch;
        private final String filePath;
        private final String CONTNET = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " 写入文件\n";

        public WriteFileTask(CountDownLatch latch, String filePath) {
            this.latch = latch;
            this.filePath = filePath;
        }
             @Override
        public void run() {
            System.out.println("开始写文件");
            try {
                //判断文件是否存在,不存在,创建文件
                File file = new File(filePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                //写入10000条
                for (int i = 0; i < 10000; i++) {
                    Files.write(Paths.get(filePath), CONTNET.getBytes(), StandardOpenOption.APPEND);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
    }
     public static void main(String[] args) {
        int N = 5;
        final String filePath = "D:\\writeTask.txt";
        CountDownLatch latch = new CountDownLatch(N);
        //1、创建线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        //2、线程池提交任务
        for (int i = 0; i < N; i++) {
            exec.execute(new WriteFileTask(latch, filePath));
        }
        //3、关闭线程池
        exec.shutdown();
        //主线程读取
        try {
            long start = System.currentTimeMillis();
            latch.await();
            System.out.println("写入完毕,总共耗时: " + (System.currentTimeMillis() - start) + " ms");
            System.out.println("开始读取......");
            List<String> list = Files.readAllLines(Paths.get(filePath));
            list.forEach(System.out::println);
            System.out.println("总共读取: " + list.size() + " 条数据!");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    }

你可能感兴趣的:(Java)