文章目錄
- 線程題
- 樹的深度遍歷
線程題
實現一個類支持100個線程同時向一個銀行賬戶中存入一元錢.需通過同步機制消除競態條件,當所有線程執行完成后,賬戶余額必須精確等于100元
package com.itheima.thread;public class ShowMeBug {private double balance; // 賬戶余額private final Object lock = new Object(); // 鎖對象,用于同步/*** 存款** @param money 存入金額*/public void deposit(double money) {synchronized (lock) { // 使用同步塊確保線程安全balance += 1;}}/*** 獲得賬戶余額*/public double getBalance() {return balance; // 修正:getBalance 不需要參數}public static void main(String[] args) throws InterruptedException{ShowMeBug account = new ShowMeBug();int numberOfThreads = 100;Thread[] threads = new Thread[numberOfThreads];//創建并啟動100個線程,每個線程存入1元for (int i = 0; i < numberOfThreads; i++) {threads[i] = new Thread(() -> {account.deposit(1.0);});threads[i].start();}// 等待所有線程完成for (int i = 0; i < numberOfThreads; i++) {threads[i].join();}// 輸出賬戶余額System.out.println("賬戶余額: " + account.getBalance());}
}
樹的深度遍歷
package com.itheima.tree;import java.util.*;public class ShowMeBug {static class Node {int id;int parentId;String name;public Node(int id, int parentId, String name) {this.id = id;this.parentId = parentId;this.name = name;}}public static void main(String[] args) {List<Node> nodeList = Arrays.asList(new Node(1, 0, "AA"),new Node(2, 1, "BB"),new Node(3, 1, "CC"),new Node(4, 3, "DD"),new Node(5, 3, "EE"),new Node(6, 2, "FF"),new Node(7, 2, "GG"),new Node(8, 4, "HH"),new Node(9, 5, "II"),new Node(10, 0, "JJ"),new Node(11, 10, "KK"),new Node(12, 10, "LL"),new Node(13, 12, "MM"),new Node(14, 13, "NN"),new Node(15, 14, "OO"));print(nodeList);}public static void print(List<Node> nodeList) {// Step 1: 構建父子關系Map<Integer, List<Node>> parentToChildren = new HashMap<>();for (Node node : nodeList) {parentToChildren.computeIfAbsent(node.parentId, k -> new ArrayList<>()).add(node);}// Step 2: 遞歸打印樹形結構printTree(parentToChildren, 0, 0);}private static void printTree(Map<Integer, List<Node>> parentToChildren, int parentId, int level) {// 獲取當前父節點的所有子節點List<Node> children = parentToChildren.getOrDefault(parentId, Collections.emptyList());// 遍歷子節點并打印for (Node child : children) {// 打印縮進(根據層級)for (int i = 0; i < level; i++) {System.out.print(" "); // 使用兩個空格表示縮進}// 打印節點名稱System.out.println(child.name);// 遞歸打印子節點的子樹printTree(parentToChildren, child.id, level + 1);}}
}