优秀代码分享

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;

/**
 * 有一个大文件,记录一段时间内百度所有的搜索记录,每行放一个搜索词,因为搜索量很大,文件非常大,搜索词数量也很多,内存放不下,求搜索次数最多的TopN个搜索词。
 * 输入:大文件
 * 输出:TopN搜索词列表
 */
public class Baidu {
    /**
     * 输出TopN搜索词列表
     *
     * @param inputFile 输入文件
     * @param n         TOP N?
     * @return TopN搜索词列表
     * @decsription 该方法未考虑连所有不重复的词语也无法完全加载的情况,只能假设当前内存能存下所有搜索词(如果时间不够,暂时使用当前办法)
     *              TODO 来不及了,先写思路,海量数据问题通常采用分而治之的解决方法,面对上面连所有不重复词语都无法加载的情况
     *              可以先加载一部分已装入wordCountMap的数据,对key也就是词语进行hash,写入到多个小文件中,这样相同key都会聚集在一个小文件中
     *              装载完成后对小文件中的数据读取,对相同key的数据相加,最后汇总所有小文件数据(还是有问题...)
     */
    public static List<String> findTopNWords(File inputFile, int n) {
        List<String> topNWords = new ArrayList<>();
        Map<String, Integer> wordCountMap = new HashMap<>();
        //读取文件
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            String line;
            //一行行读取数据,避免一次性加载不了
            while ((line = reader.readLine()) != null) {
                //每行放一个搜索词,没说是不是句子,假设按照  aa bb  cc对语句按照单词拆分
                String[] words = line.split("\\s+");
                for (String word : words) {
                    //单词对应次数+1
                    wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();//TODO 引入日志组件后用log.error替换
        }
        //转换成List去用sort的API,方便
//        List<Map.Entry<String, Integer>> sortedWordList = new ArrayList<>(wordCountMap.entrySet());
//        sortedWordList.sort(Comparator.comparing(Map.Entry::getValue).reversed());
//        sortedWordList.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
        //找TOP N
//        for (int i = 0; i < n && i < sortedWordList.size(); i++) {
//            topNWords.add(sortedWordList.get(i).getKey());
//        }
        PriorityQueue<Map.Entry<String, Integer>> maxHeap =
                new PriorityQueue<>((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
        for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
            maxHeap.offer(entry);
        }
        if (!maxHeap.isEmpty()) {
            for (int i = 0; i < n; i++) {
                topNWords.add(maxHeap.poll().getKey());
            }
        }
        return topNWords;
    }

    public static void main(String[] args) {
        File inputFile = new File("D:/topn.txt");
        int topN = 10;
        List<String> topNWords = findTopNWords(inputFile, topN);
        System.out.println("TopN搜索词列表:");
        for (String word : topNWords) {
            System.out.println(word);
        }
    }
}

import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ProducerConsumerExample {
    public static void main(String[] args) {
        // 创建共享的并发队列
        Queue<Integer> queue = new ConcurrentLinkedQueue<>();
//        Queue<Integer> queue = new LinkedBlockingQueue<>();
        // 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000));
        AtomicInteger ai = new AtomicInteger(0);
        // 提交生产者和消费者任务
        for (int i = 0; i < 2; i++) {
            executor.submit(new Producer(queue, ai));
        }
        for (int i = 0; i < 2; i++) {
            executor.submit(new Consumer(queue));
        }
        // 关闭线程池
        executor.shutdown();
    }

    // 生产者任务
    static class Producer implements Runnable {
        private final Queue<Integer> queue;
        private final AtomicInteger value;

        public Producer(Queue<Integer> queue, AtomicInteger value) {
            this.value = value;
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                // 生产新的数据并添加到队列
                int val = value.incrementAndGet();
                System.out.println("Produced: " + val);
                queue.offer(val);
                // 模拟生产耗时
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 消费者任务
    static class Consumer implements Runnable {
        private final Queue<Integer> queue;

        public Consumer(Queue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                // 从队列中取出数据并消费
                Integer value = queue.poll();
                if (value != null) {
                    System.out.println("Consumed: " + value);
                }
                // 模拟消费耗时
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
System.out.println(Arrays.toString(bubbleSort(new int[]{64, 34, 25, 12, 22, 11, 90})));

private static int[] bubbleSort(int[] array) {
    int n = array.length;
    //避免越界
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    return array;
}

public static void main(String[] args) {
    AtomicInteger ai = new AtomicInteger(1);
    Semaphore a = new Semaphore(1);
    Semaphore b = new Semaphore(0);
    Semaphore c = new Semaphore(0);
    try (ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100,
            1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(100));) {
        executor.submit(new Thread(() -> {
            printNum(ai, a, b);
        }));
        executor.submit(new Thread(() -> {
            printNum(ai, b, c);
        }));
        executor.submit(new Thread(() -> {
            printNum(ai, c, a);
        }));
    }
}

private static void printNum(AtomicInteger ai, Semaphore cur, Semaphore next) {
    while (ai.get() <= 100) {
        try {
            cur.acquire();
            //必要--在多线程环境中,有可能一个线程已经通过了循环条件(ai.get() <= MAX_NUMBER)并且获取了信号量,而另一个线程(它已经在等待中)也通过了循环条件。如果没有额外的检查,两个线程可能在释放信号量之前都会打印超过上限的数字,导致输出不正确。
            if (ai.get() <= 100) {
                System.out.println(ai.getAndIncrement());
            }
            next.release();
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }
}

相关推荐

  1. 优秀代码分享

    2024-07-16 11:10:04       23 阅读
  2. 优化代码分支

    2024-07-16 11:10:04       42 阅读
  3. 代码分享

    2024-07-16 11:10:04       41 阅读
  4. -代码分享-

    2024-07-16 11:10:04       40 阅读
  5. 代码重构实践分享

    2024-07-16 11:10:04       17 阅读
  6. Github、Gitee优秀的开源项目分享

    2024-07-16 11:10:04       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 11:10:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 11:10:04       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 11:10:04       58 阅读
  4. Python语言-面向对象

    2024-07-16 11:10:04       69 阅读

热门阅读

  1. 题解-运动会

    2024-07-16 11:10:04       22 阅读
  2. DangerWind-RPC-framework---五、服务端的反射调用

    2024-07-16 11:10:04       24 阅读
  3. LeetCode 162. 寻找峰值

    2024-07-16 11:10:04       23 阅读
  4. 来聊聊Socket,WebSocket和MQTT的区别

    2024-07-16 11:10:04       22 阅读
  5. 探索老年综合评估实训室的功能与价值

    2024-07-16 11:10:04       22 阅读
  6. com.alibaba.fastjson与net.sf.json相互转换

    2024-07-16 11:10:04       20 阅读