简体   繁体   English

我如何创建每次将新元素添加到ArrayList时都会触发的事件

[英]How do I create a event that fires up every time a new element is added to ArrayList

I want to create an method that fires up every time a new message is added to the groupchat arraylist. 我想创建一个方法,每次将新消息添加到groupchat arraylist时都会启动。 Pseudo code: 伪代码:

public void listenForChange(){
   while(true){
        if(new message is added to the groupchat){
             System.out.println(print the last added message);
        }
   }
 }

What I have tried, but doesn't work: 我尝试过但无法使用的内容:

public class Groupe{
   ArrayList<String> groupechat;
   int liveChange;

 public void listenForChange() {
    while(true){
        if (groupchat.size() > liveChange){
            liveChange= gruppenchat.size();
            System.out.println(gruppenchat.get(liveChange-1));
        }
    }
}

Test class: 测试类别:

public class testGruppen extends Thread {
Gruppe gruppe;


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

public void run() {
    System.out.println("listen");
    gruppe.listenForChange();
}
public static void main(String[] args) {
    testGruppen test = new testGruppen();
    test.start();
    test.gruppe.write("1"); // write just adds a new String to groupchat
    test.gruppe.write("2");
    test.gruppe.write("3");
    test.gruppe.write("4");

}

} }

Output: 4 instead of 1\\n 2\\n 3\\n 4\\n 输出: 4而不是1\\n 2\\n 3\\n 4\\n

What about using decorator: 怎样使用装饰器:

public static void main(String... args) {
    List<Integer> group = new FireEventListDecorator<>(new ArrayList<>());
    for (int i = 0; i < 3; i++)
        group.add(i);
}

public static class FireEventListDecorator<E> extends AbstractList<E> {

    private final List<E> delegate;

    public FireEventListDecorator(List<E> delegate) {
        this.delegate = delegate;
    }

    @Override
    public void add(int index, E element) {
        delegate.add(index, element);
        fireEvent(element);
    }

    @Override
    public E get(int index) {
        return delegate.get(index);
    }

    @Override
    public int size() {
        return delegate.size();
    }

    private void fireEvent(E element) {
        System.out.println("add: " + element);
    }
}

To avoid a CPU wasteful while (true) loop with polling, use a call-back method via an observer/listener pattern. 为了避免CPU while (true)轮询时浪费while (true)循环,请通过观察者/侦听器模式使用回调方法。 One way to do this is to give your class that holds the ArrayList a PropertyChangeSupport instance, allow it to accept listeners, and then in the method that changes the ArrayList, notify listeners. 一种方法是给持有ArrayList的类一个PropertyChangeSupport实例,允许它接受侦听器,然后在更改ArrayList的方法中通知侦听器。

eg, 例如,

public class Group {
    // property listened to: ADD_TEXT
    public static final String ADD_TEXT = "add text";

    // the support object
    private PropertyChangeSupport support = new PropertyChangeSupport(this);
    private List<String> chatText = new ArrayList<>();

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        support.addPropertyChangeListener(ADD_TEXT, listener);
    }

    public void addText(String text) {
        String oldValue = "";
        String newValue = text;
        chatText.add(text + "\n");

        // notify listeners
        support.firePropertyChange(ADD_TEXT, oldValue, newValue);
    }
}

And then it can be used like so: 然后可以像这样使用它:

public class TestGroupChat {
    public static void main(String[] args) {
        final Group group = new Group();
        group.addPropertyChangeListener(new GroupListener());
        final String[] texts = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

        new Thread(() -> {
            for (String text : texts) {
                group.addText(text);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {}
            }
        }) .start();
    }

    private static class GroupListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            // call back method that is called any time the listened-to
            // property has been changed
            System.out.println("Notification: "+ evt.getNewValue());
        }
    }
}

You should take a look at LinkedBlockingQueue class . 您应该看看LinkedBlockingQueue类 This class is useful when you want to wake up a thread when a new element is added to a queue. 当您想要在将新元素添加到队列时唤醒线程时,此类非常有用。 In the example below, everytime you add a new message to the queue, the thread will print the message and wait for the next message. 在下面的示例中,每次将新消息添加到队列时,线程都会打印该消息并等待下一条消息。

public class Foo extends Thread {

    LinkedBlockingQueue<String> messagesQueue;

    public Foo(LinkedBlockingQueue<String> messagesQueue) {
        this.messagesQueue = messagesQueue;
    }

    @Override
    public voir run() {
        while(true) {
            String message = messagesQueue.take();
           //The thread will sleep until there is a new message in the queue.
           System.out.println(message);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次都需要循环添加新的ArrayList吗? - Do I need to new ArrayList in loop every time? 如何使用每个新参数在ArrayList中创建新对象 - How to create new object in ArrayList with every new arguments 每次更改变量时如何生成事件流? - How Do I Generate Event Stream Every Time Variable Is Changed? 如何创建一个 arraylist 的选定文件(或 url 列表),然后使用数组的每个元素 - Android - How can I create an arraylist of selected files (or url list) and then use every element of the array - Android 每次用户在Java中输入值时,如何创建更新ArrayList的表? - How can I create a table that updates an ArrayList every time a user enters a value in Java? 如何撤消添加到ArrayList的元素 - How to undo an added element to an ArrayList 添加第一个元素或删除最后一个元素时触发事件的设置 - Set that fires event when first element is added, or last one is removed 如何在每次单击按钮时创建一个新的 object? - How do I create a new object on every button click? 将对象添加到arraylist时,如何在Springboot上创建触发器? - How can I create a trigger on Springboot when an object is added to an arraylist? 如何更新 arraylist 中的元素? - How do I update the element inside the arraylist?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM