1

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?

adam0101
  • 29,096
  • 21
  • 96
  • 174

3 Answers3

5

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • `BeginInvoke` will use the thread pool, is there such a concept in Java? - Sorry, I should have taken a second to follow your "Executors" link! Thanks – weston Mar 12 '12 at 14:50
  • When I try this I get the error "The method run() of type new Runnable(){} must override a superclass method". – adam0101 Mar 12 '12 at 14:51
  • 1
    @adam0101 Not sure why: it works on my machine. What version of Java JDK are you using? If you use Java 5 or earlier, you might need to remove the `@Override` annotation (http://stackoverflow.com/questions/2135975/can-i-get-java-5-to-ignore-override-errors). – assylias Mar 12 '12 at 14:56
2

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);
Joel
  • 16,474
  • 17
  • 72
  • 93
1

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

Community
  • 1
  • 1
KeithS
  • 70,210
  • 21
  • 112
  • 164