问题
Just like we have AsyncTask in android , what options do we have in Java to perform task running in background(different Thread) and as well communicate with the main Thread easily .
I have found things like
1.Worker Threads and
2.swing workers
please let me know if these are the correct classes to do such work , as well what else i can use to do above mention work
回答1:
For multi-threading/tasking in general, Java has terrific concurrency support. Check out java.util.concurrent. And to communicate with the main thread perhaps java.util.obsever and java.util.observable.
回答2:
If you want parallel tasks in general (not related to any UI toolkit), and you don't alrady use a framework that offers some high-level concurrency mechanisms (like the eclipse Job API), you should have a look at the java.util.concurrent
package - especially Executor
and ExecutorService
.
Example:
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
// somewhere else:
executor.execute(myRunnableTask); // myRunnableTask is a Runnable
// or, if you want to have more control
Future<Double> futureResult = executor.submit(myCallableCalculation);
// ...
Double result = futureResult.get(); // waits until calculation completes
See also:
- http://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html
- http://www.vogella.com/articles/JavaConcurrency/article.html
回答3:
For multi-threading/tasking in general, Java has terrific concurrency support. Check out java.util.concurrent. And to communicate with the main thread perhaps java.util.obsever and java.util.observable.
来源:https://stackoverflow.com/questions/20369198/perform-background-task-in-java