Java equivalent of C# Action.BeginInvoke
本文关键字:Action BeginInvoke of equivalent Java | 更新日期: 2023-09-27 18:27:35
我有这个C#代码:
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
据我所知,它只是异步运行MyFunction。你能用Java做同样的事情吗?
这就是在Java中如何在自己的线程中运行操作:
new Thread(new Runnable() {
@Override
public void run() {
aFunctionThatRunsAsynchronously();
}
}).start();
还有其他更高级别的框架可以让你更好地控制事情的运行方式,比如Executor,它可以用来安排事件。
从本质上讲,ExecutorService提供了我能想到的最接近的服务。以下是如何使用ExecutorService运行方法async,然后稍后获得返回值:
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