[英]Java equivalent of C# Action.BeginInvoke
我有这个C#代码:
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
据我所知,它只是异步运行MyFunction。 您可以在Java中做同样的事情吗?
在本机,ExecutorService提供了我能想到的最接近的东西。 您可以使用以下方法使用ExecutorService运行异步方法,然后稍后获取返回值:
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
Future<String> future = executor.submit(new Callable<String>() {
return getSomeLongRunningSomethingHere();
});
//... do other stuff here
String rtnValue = future.get(); //get blocks until the original finishes running
System.out.println(rtnValue);
这在某种程度上与Java中的异步事件调度有关。 基本上,您可以将要运行的方法构造为实现Callable或Runnable的类。 Java没有像C#一样将“方法组”引用为变量或参数的能力,因此Java中的事件处理程序都是实现定义监听器的接口的类。
尝试这样的事情:
Executor scheduler = Executors.newSingleThreadExecutor();
//You'd have to change MyFunction to be a class implementing Callable or Runnable
scheduler.submit(MyFunction);
有关Oracle Java文档的更多信息,请参见:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.