如何实现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
Thread Visibility & Synchronization Problems
- Your
liveChangevariable isn't markedvolatile, and there's no synchronization around modifications togroupchat. 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). ArrayListis not thread-safe—concurrent writes/reads without synchronization can cause unexpected behavior or evenConcurrentModificationException.
- Your
Busy Waiting Wastes Resources
- The
while(true)loop inlistenForChange()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.
- The
Variable Name Typos
- There are inconsistent spellings like
gruppenchatvsgroupchatwhich would cause compilation errors (I assume this was a typo in your code snippet).
- There are inconsistent spellings like
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
synchronizedensures only one thread can accessgroupchatandliveChangeat 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()callsnotify(), 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
相关产品推荐
相关产品推荐

