我有这样的C#代码:相当于Java的C#Action.BeginInvoke
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
其中,从我所知道的,只是运行MyFunction的异步方式。你可以在Java中做同样的事情吗?
我有这样的C#代码:相当于Java的C#Action.BeginInvoke
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
其中,从我所知道的,只是运行MyFunction的异步方式。你可以在Java中做同样的事情吗?
这是你如何可以运行在自己的线程Java中的作用:
new Thread(new Runnable() {
@Override
public void run() {
aFunctionThatRunsAsynchronously();
}
}).start();
有迹象表明,给你的东西是如何运行的,例如Executors更多的控制提供其他高级框架,它可以例如用于schedule events。
这与Asynchronous Event Dispatch in Java有些相关。基本上,您可以将您希望运行的方法构造为实现Callable或Runnable的类。 Java不能像C#那样将“方法组”引用为变量或参数,因此即使Java中的事件处理程序也是实现定义侦听器的接口的类。
尝试是这样的:从Oracle Java文档
Executor scheduler = Executors.newSingleThreadExecutor();
//You'd have to change MyFunction to be a class implementing Callable or Runnable
scheduler.submit(MyFunction);
更多阅读:
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
本身的的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);
'BeginInvoke'将使用线程池,有没有在Java中这样的概念? - 对不起,我应该花一秒钟来关注你的“执行者”链接!谢谢 – weston 2012-03-12 14:50:47
是的:http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html – assylias 2012-03-12 14:51:43
当我尝试这个时,我得到错误“类型new Runnable(){}的方法run()必须覆盖超类方法“。 – adam0101 2012-03-12 14:51:47