简体   繁体   English

有什么办法可以在Java中使用变量来进行事件? 内部例子

[英]Is there any way to have events with a variable in Java? Example inside

Say, I have a SystemQueue class that wraps a Queue object. 说,我有一个包装队列对象的SystemQueue类。 I add to this queue using systemQueue.add(whatever), and I have a different object thats a Runnable that checks the queue, and if its not empty, takes from the queue and uses "whatever" in its code. 我使用systemQueue.add(whatever)添加到此队列中,并且有一个不同的对象,那就是Runnable,它检查队列,如果不为空,则从队列中取出并在其代码中使用“ whatever”。 Is there any way to do this besides having an infinite loop in the run like 除了在运行中有无限循环外,还有什么方法可以做到这一点

    run(){
        while(true){
            if(!systemQueue.isEmpty()){
                  todo
             }
       }
   }

and have that run forever? 并永远运行吗? What I'm asking is, how can I code using event-based-coding in java? 我要问的是,如何在Java中使用基于事件的编码进行编码?

Is there any way I can add an eventListener to the queue inside SystemQueue, and if the queue changes, call out to SystemExecutor and have it run? 有什么方法可以将eventListener添加到SystemQueue内部的队列中,如果队列发生更改,请调出SystemExecutor并使其运行?

Queue itself doesn't provide that option. Queue本身不提供该选项。 You can implement your own listener/event pair though. 但是,您可以实现自己的侦听器/事件对。

Event: 事件:

public class SystemEvent extends java.util.EventObject{
    public SystemEvent(SystemQueue src){
        super(src);
    }

    public SystemQueue getSource(){
         return (SystemQueue) super.getSource();
    }
}

Listener: 监听器:

public interface SystemListener extends java.util.EventListener{
    public void eventQueued(SystemEvent e);
}

in SystemQueue: 在SystemQueue中:

ArrayList<SystemListener> listeners = new ArrayList<>();

protected void fireEventQueued(){
    SystemEvent e = new SystemEvent(this);

    listeners.forEach(l -> l.eventQueued(e));
}

public void addSystemListener(SystemListener l){
     listeners.add(l);
}

public void add(something){
    //add something
    fireEventQueued();
}

Now all you need to do is make SystemExecutor implement SystemListener and add the instance as listener. 现在,您需要做的就是使SystemExecutor实现SystemListener并将实例添加为侦听器。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM