You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现ArrayList新增元素触发事件?现有代码输出异常求助

Hey there! Let's break down why your code only outputs "4" instead of all the messages, and fix it step by step:

Key Issues in Your Code

  1. Thread Visibility & Synchronization Problems

    • Your liveChange variable isn't marked volatile, and there's no synchronization around modifications to groupchat. This means the listener thread might not see updates made by the main thread (JVM can cache variables in thread-local memory, leading to stale reads).
    • ArrayList is not thread-safe—concurrent writes/reads without synchronization can cause unexpected behavior or even ConcurrentModificationException.
  2. Busy Waiting Wastes Resources

    • The while(true) loop in listenForChange() is a busy wait that hogs CPU. Instead, we should use Java's wait/notify mechanism to let the listener thread sleep until a new message arrives.
  3. Variable Name Typos

    • There are inconsistent spellings like gruppenchat vs groupchat which would cause compilation errors (I assume this was a typo in your code snippet).

Fixed Code Implementation

Modified Gruppe Class

import java.util.ArrayList;
import java.util.List;

public class Gruppe {
    private List<String> groupchat;
    private int liveChange;

    public Gruppe(String name) {
        groupchat = new ArrayList<>();
        liveChange = 0;
    }

    // Synchronize write to ensure thread-safe updates and notify listeners
    public synchronized void write(String message) {
        groupchat.add(message);
        notify(); // Wake up waiting listener thread
    }

    public synchronized void listenForChange() {
        try {
            while (true) {
                // Wait until there are new messages
                while (groupchat.size() <= liveChange) {
                    wait(); // Releases lock and sleeps until notified
                }
                // Process all new messages (handles cases where multiple messages are added at once)
                while (groupchat.size() > liveChange) {
                    liveChange++;
                    System.out.println(groupchat.get(liveChange - 1));
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("Message listener interrupted");
        }
    }
}

Modified Test Class

public class TestGruppen extends Thread {
    private Gruppe gruppe;

    public TestGruppen() {
        gruppe = new Gruppe("Monday");
    }

    @Override
    public void run() {
        System.out.println("Listening for new messages...");
        gruppe.listenForChange();
    }

    public static void main(String[] args) throws InterruptedException {
        TestGruppen test = new TestGruppen();
        test.start();
        
        // Give the listener thread time to start waiting
        Thread.sleep(100);
        
        test.gruppe.write("1");
        test.gruppe.write("2");
        test.gruppe.write("3");
        test.gruppe.write("4");
        
        // Uncomment below to stop the listener thread when done
        // test.interrupt();
    }
}

What Changed & Why

  • Synchronized Methods: Using synchronized ensures only one thread can access groupchat and liveChange at a time, preventing race conditions and ensuring visibility of updates across threads.
  • Wait/Notify: Replaces busy waiting with efficient thread waiting. The listener sleeps until write() calls notify(), which wakes it up to process new messages.
  • Thread Sleep: A short Thread.sleep(100) gives the listener thread time to enter its waiting state before the main thread starts adding messages—this ensures messages are printed as they're added, not all at once.

内容的提问来源于stack exchange,提问作者quinzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:25:04