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
精彩评论