Perform Background task in java

2019-06-13 06:58发布

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

3条回答
做自己的国王
2楼-- · 2019-06-13 07:33

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.

查看更多
▲ chillily
3楼-- · 2019-06-13 07:34

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:

查看更多
Evening l夕情丶
4楼-- · 2019-06-13 07:49

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.

查看更多
登录 后发表回答