开发者

Asynchronous task pattern in Java

开发者 https://www.devze.com 2023-02-14 09:30 出处:网络
I\'m moving from C# to Java, and I need to implement a set of asynchronous tasks. I have a good knowledge of Java threading, but I liked .NET\'s BeginInvoke and EndInvoke methods because they allowed

I'm moving from C# to Java, and I need to implement a set of asynchronous tasks.

I have a good knowledge of Java threading, but I liked .NET's BeginInvoke and EndInvoke methods because they allowed me to switch from synchronous to asynchronous tasks with ease.

In my case, if I have a set of I/O intensive operations (suitable for changing to async) like the following:

DoOperation1();
DoOperation2();
DoOperation3();

in .NET I would easily do something like:

BeginInvoke(DoOperation1);
BeginInvoke(DoOperation2);
BeginInvoke(DoOperation3);
EndInvoke(Result1);
EndInvoke(Result2);
EndInvoke(Result3);

Briefly, my question is:开发者_如何学Python is there anything similar in Java, or do I need to use threads manually "the old way"?

Thank you.


You probably want to use futures in Java. You submit a task to an ExecutorService and receive a Future<T> back which you can ask view in a similar way to Task<T> from the .NET 4 TPL... you can ask a future for its result in a blocking manner, or with a timeout, ask if it's done etc.

Working with Callable<T> isn't as neat as using delegates in C# via method group conversions and lambda expressions, but the basic ideas are similar.


I think you'd probably want to use ExecutorService alongside Runnable or Callable classes that wrap the implementation of the jobs you're trying to run.

An example:

SomeTask someTask1 = ...
SomeTask someTask2 = ...

executorService.execute(someTask1);
executorService.execute(someTask2);

executorService.shutdown(); //Close down the service
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号