I have this C# code:
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
which, from what I can tell, just runs MyFunction asynchronously. Can you do the same thing in Java?
I have this C# code:
Action action = MyFunction;
action.BeginInvoke(action.EndInvoke, action);
which, from what I can tell, just runs MyFunction asynchronously. Can you do the same thing in Java?
This is how you could run an action in its own thread in Java:
new Thread(new Runnable() {
@Override
public void run() {
aFunctionThatRunsAsynchronously();
}
}).start();
There are other higher-level frameworks available that give you more control on how things are run such as Executors, which can for example be used to schedule events.
Natively, the ExecutorService provides the closest I can think of. Here's how you can use the ExecutorService to run a method async and then get the return value later:
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);
This is somewhat related to Asynchronous Event Dispatch in Java. Basically, you can structure the method you want to run as a class implementing Callable or Runnable. Java doesn't have the ability to refer to a "method group" as a variable or parameter, like C# does, so even event handlers in Java are classes implementing an interface defining the listener.
Try something like this:
Executor scheduler = Executors.newSingleThreadExecutor();
//You'd have to change MyFunction to be a class implementing Callable or Runnable
scheduler.submit(MyFunction);
More reading from the Oracle Java docs:
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