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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
When I try this I get the error "The method run() of type new Runnable(){} must override a superclass method".
@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 (stackoverflow.com/questions/2135975/…).
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);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.