在新线程上执行Java回调 [英] Executing Java callback on a new thread

查看:145
本文介绍了在新线程上执行Java回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此项目中, Manager 执行事件排队,并返回事件的结果使用回调(回调不会扩展 Runnable )。管理器在单独的线程上运行,分派事件。一旦事件终止,同一个线程调用回调。这意味着下一个事件将不会在上一个事件的回调终止之前被分派。为了避免这种情况,我虽然有经理为每个回调创建一个新的线程,并执行回调。

On this project, a Manager performs event queuing, and to return the result of the event a callback is used (the callback does not extend Runnable). The manager runs on a separate thread, dispatching the events. Once the events terminate, this same thread calls the callbacks. This means that the next event will not be dispatched before the callback of the previous event terminates. In order to avoid this, I though about having the manager create a new thread for each callback, and executing the callbacks there. How good is this solution in terms of design practices, and is there a better way to achieve this?

推荐答案

一个简单的回调代码:

import java.util.concurrent.*;
import java.util.*;

public class CallBackDemo{
    public CallBackDemo(){
        System.out.println("creating service");
        ExecutorService service = Executors.newFixedThreadPool(10);

        try{
            for ( int i=0; i<10; i++){
                Callback callback = new Callback(i+1);
                MyCallable myCallable = new MyCallable((long)i+1,callback);
                Future<Long> future = service.submit(myCallable);
                //System.out.println("future status:"+future.get()+":"+future.isDone());
            }
        }catch(Exception err){
            err.printStackTrace();
        }
        service.shutdown();
    }
    public static void main(String args[]){
        CallBackDemo demo = new CallBackDemo();
    }
}
class MyCallable implements Callable<Long>{
    Long id = 0L;
    Callback callback;
    public MyCallable(Long val,Callback obj){
        this.id = val;
        this.callback = obj;
    }
    public Long call(){
        //Add your business logic
        System.out.println("Callable:"+id+":"+Thread.currentThread().getName());
        callback.callbackMethod();
        return id;
    }
}
class Callback {
    private int i;
    public Callback(int i){
        this.i = i;
    }
    public void callbackMethod(){
        System.out.println("Call back:"+i);
        // Add your business logic
    }
}

creating service
Callable:1:pool-1-thread-1
Call back:1
Callable:2:pool-1-thread-2
Call back:2
Callable:8:pool-1-thread-8
Call back:8
Callable:3:pool-1-thread-3
Call back:3
Callable:10:pool-1-thread-10
Callable:4:pool-1-thread-4
Call back:10
Callable:7:pool-1-thread-7
Call back:7
Callable:6:pool-1-thread-6
Call back:6
Callable:9:pool-1-thread-9
Callable:5:pool-1-thread-5
Call back:9
Call back:4
Call back:5

摘要:


  1. 经理替换为您偏好选择的 ExecutorService

  2. 您可以将 Callaback 对象传递给 Callable / Runnable 对象或者可以创建回调 Callable / Runnable 中的对象。在我的例子中,我已经明确地将 Callback 对象传递给 Callable

  3. 在返回结果之前, Callable 对象调用回调方法。如果你想阻止进一步进行,除非你得到当前事件的响应,只要取消注释以下行。

  1. Replace Manager with ExecutorService of your preferred choice.
  2. Either your can pass Callaback object to Callable/Runnable object Or you can create Callback object inside Callable/Runnable. In my example, I have explicitly passed Callback object to Callable.
  3. Before returning the result, Callable object invokes Callback method. If you want to block on proceeding further unless you get response from current event, just uncomment below line.

System.out.println("future status:"+future.get()+":"+future.isDone());


我想你会避开它因此保持在上面行评论。您不必为 Callback 方法调用创建新线程。如果您想要异步处理 Callback 事件,您可以再创建一个 ExecutorService 并提交事件。

I think you are going to avoid it and hence keep above line commented. You don't have to create new thread for Callback method invocation. If you want to process Callback event asynchronously, you can create one more ExecutorService and submit the event.

这篇关于在新线程上执行Java回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆