遇到的题目

第一个线程打印10次a ,第二个线程打印10次吧,第三个线程打印10次c,三个线程交替打印abc


public class PrintABC {
    private static final Object lock = new Object();
    private static int count = 0;
    
    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintThread("A", 0));
        Thread threadB = new Thread(new PrintThread("B", 1));
        Thread threadC = new Thread(new PrintThread("C", 2));
        
        threadA.start();
        threadB.start();
        threadC.start();
    }
    
    static class PrintThread implements Runnable {
        private String name;
        private int id;
        
        public PrintThread(String name, int id) {
            this.name = name;
            this.id = id;
        }
        
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    while (count % 3 != id) {
                        try {
                            lock.wait(); // 当前线程等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    System.out.print(name);
                    count++;
                    
                    lock.notifyAll(); // 唤醒其他等待的线程
                }
            }
        }
    }
}

遇到的题目_第1张图片

有一个string变量,如何找出字符串中出现次数最多的字符

import java.util.HashMap;
import java.util.Map;

public class MostFrequentChar {
    public static char findMostFrequentChar(String str) {
        Map charCount = new HashMap<>();
        
        // 统计每个字符出现的次数
        for (char c : str.toCharArray()) {
            if (charCount.containsKey(c)) {
                charCount.put(c, charCount.get(c) + 1);
            } else {
                charCount.put(c, 1);
            }
        }
        
        char mostFrequentChar = '\0';
        int maxCount = 0;
        
        // 找出出现次数最多的字符
        for (Map.Entry entry : charCount.entrySet()) {
            char c = entry.getKey();
            int count = entry.getValue();
            
            if (count > maxCount) {
                mostFrequentChar = c;
                maxCount = count;
            }
        }
        
        return mostFrequentChar;
    }
    
    public static void main(String[] args) {
        String str = "abracadabra";
        char mostFrequentChar = findMostFrequentChar(str);
        System.out.println("出现次数最多的字符: " + mostFrequentChar);
    }
}

遇到的题目_第2张图片

你可能感兴趣的:(笔记题目,java,开发语言)