java java中的AsyncTask等价物
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36272642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AsyncTask equivalent in java
提问by Jdavis649
In android there is the AsyncTask which runs a thread and then i can use the method on post execute to interact with main thread again. is there an equivalent to this in java? i am trying to run a timer on separate thread (doInBackground) and once the time is finished it will then allow me to interact with the main theard to restart a service (onPostExecute will restart service)
在android中有运行线程的AsyncTask,然后我可以在执行后使用该方法再次与主线程交互。在java中是否有等价物?我正在尝试在单独的线程(doInBackground)上运行一个计时器,一旦时间结束,它将允许我与主线程交互以重新启动服务(onPostExecute 将重新启动服务)
回答by Tuan Do
I'm not Android developer but I think it could be easily implemented by using a CompletableFutureon Java 8:
我不是 Android 开发人员,但我认为它可以通过在 Java 8 上使用CompletableFuture轻松实现:
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CompletableFuture;
import javax.swing.SwingUtilities;
public abstract class AsyncTask <Params, Progress, Result> {
protected AsyncTask() {
}
protected abstract void onPreExecute();
protected abstract Result doInBackground(Params... params) ;
protected abstract void onProgressUpdate(Progress... progress) ;
protected abstract void onPostExecute(Result result) ;
final void publishProgress(Progress... values) {
SwingUtilities.invokeLater(() -> this.onProgressUpdate(values) );
}
final AsyncTask<Params, Progress, Result> execute(Params... params) {
// Invoke pre execute
try {
SwingUtilities.invokeAndWait( this::onPreExecute );
} catch (InvocationTargetException|InterruptedException e){
e.printStackTrace();
}
// Invoke doInBackground
CompletableFuture<Result> cf = CompletableFuture.supplyAsync( () -> doInBackground(params) );
// Invoke post execute
cf.thenAccept(this::onPostExecute);
return this;
}
}
回答by Daniel S.
Solution Tailored for You
为您量身定制的解决方案
In short, look at java: run a function after a specific number of seconds.
简而言之,看java: run a function after a specific number of seconds。
For your purpose, you don't need an AsyncTask
. AsyncTask
is for running something that needs the time, but you would prefer it didn't (e.g. a complex calculation or fetching data from the internet). It's for getting around the problem that you would need to wait.
What you want to do instead is to introduce a delay, or more precisely you want to schedule some action to happen after a delay. You can use a class like AsyncTask
for this as well, but it's an overkill and results in more complicated code. You should instead use a class which is tailored for delayed execution, which is Timer
and TimerTask
:
为了您的目的,您不需要AsyncTask
. AsyncTask
用于运行需要时间的东西,但您希望它不需要(例如,复杂的计算或从 Internet 获取数据)。这是为了解决您需要等待的问题。
相反,您想要做的是引入延迟,或者更准确地说,您想要安排一些操作在延迟之后发生。您也可以AsyncTask
为此使用类似的类,但这是一种矫枉过正并导致更复杂的代码。您应该改为使用为延迟执行量身定制的类,即Timer
和TimerTask
:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
Equivalent of AsyncTask
in standard Java
相当于AsyncTask
标准 Java
Note that AsyncTask
is connected to a UI concept (UI = user interface), because it may only be started from the UI thread. It's not for generally running something asynchronously.
注意AsyncTask
是连接到一个 UI 概念(UI = 用户界面),因为它可能只能从 UI 线程启动。它通常不用于异步运行某些东西。
Thus, the best matching equivalent of android's AsyncTask
is SwingWorker
in Java. Swing is Java's standard UI framework. It has a similar concept as android with a UI thread. In Swing, this thread is called the Event Dispatch Thread. Hence, the design of SwingWorker
is also very similar to AsyncTask
. Even the doInBackground()
method has the same name in both classes.
因此,与 android 的最佳匹配等效项AsyncTask
是SwingWorker
Java。Swing 是 Java 的标准 UI 框架。它与带有 UI 线程的 android 具有相似的概念。在 Swing 中,这个线程称为Event Dispatch Thread。因此, 的设计SwingWorker
也非常类似于AsyncTask
。甚至该doInBackground()
方法在两个类中都具有相同的名称。
Asynchronous Execution in General
一般异步执行
If your requirement is not related to a UI and you only want to source some time consuming operation out so it executes asynchronously, then you need to look at executors. There is a variety of different ways to use executors for many different purposes, so this would go beyond the scope of this answer. If you are interested in further information, start with Jakob Jenkov's tutorial on ExecutorService.
如果您的需求与 UI 无关,并且您只想获取一些耗时的操作以便异步执行,那么您需要查看执行程序。有多种不同的方法可以将执行程序用于许多不同的目的,因此这超出了本答案的范围。如果您对更多信息感兴趣,请从Jakob Jenkov 关于 ExecutorService 的教程开始。