开发者

What is the best way to convert a synchronous method call to an asynchronous one?

开发者 https://www.devze.com 2023-02-18 08:11 出处:网络
I have several methods (involving network operations) which take quite a long time. I want to call them asynchronously and check the status from time to time开发者_如何转开发. What\'s the recommended

I have several methods (involving network operations) which take quite a long time. I want to call them asynchronously and check the status from time to time开发者_如何转开发. What's the recommended way to do it in Java?


If you are using java 5 or above, you can use Executor otherwise you can use threads.


I would use a FutureTask. You give it the task, you can provide code to be run when the task is over (the protected done method), and you can check it's status with the isDone method. If you're writing a swing application you could also use SwingWorker


Asynchronous execution is done with Thread in Java. If you are new to that begin with Thread and Runnable and try to implement some code with them. When you got the idea switch to java.util.concurrent package.


Take a look at the Future interface and the associated documentation: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html

0

精彩评论

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

关注公众号