优秀代码分享

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();
        }
    }
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

princeAladdin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值