Java 在另一个线程中同步运行函数
如何在另一个线程中同步运行函数,这意味着主UI线程有一个函数调用另一个函数,该函数在另一个线程上执行其工作,等待新线程完成并返回值:Java 在另一个线程中同步运行函数,java,android,Java,Android,如何在另一个线程中同步运行函数,这意味着主UI线程有一个函数调用另一个函数,该函数在另一个线程上执行其工作,等待新线程完成并返回值: int mainFunction() //this function is on the main UI thread { return doWorkOnNewThread(); } int doWorkOnNewThread() { //do work on new thread } 您可以为此使用异步任务,即使它是异步的。您可以根据需要使用on
int mainFunction() //this function is on the main UI thread
{
return doWorkOnNewThread();
}
int doWorkOnNewThread()
{
//do work on new thread
}
您可以为此使用异步任务,即使它是异步的。您可以根据需要使用onPostExecute和onProgressUpdate回调来更新值。我还应该注意到,您可能不希望执行此同步操作,因为它会阻塞您的UI线程,这可能会导致应用程序不响应警报,具体取决于计算所需的时间。在单独的线程中执行代码的方法很少。 你可以看看这个 我想那会满足你的要求
protected void onPreExecute () {
// you can show some ProgressDialog indicating to the user that thread is working
}
protected Type doInBackground(String... args) {
doWorkOnNewThread()
// do your stuff here
}
protected void onPostExecute(Type result) {
// here you can notify your activity that thread finished his job and dismiss ProgressDialog
}
你有两条路:
1.阿森塔克
2.处理程序公共静态T runSynchronouslyOnBackgroundThread(最终可调用){
public static <T> T runSynchronouslyOnBackgroundThread(final Callable<T> callable) {
T result = new Thread() {
T callResult;
@Override
public void run() {
try {
callResult = callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
T startJoinForResult() {
start();
try {
join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return callResult;
}
}.startJoinForResult();
return result;
}
T结果=新线程(){
T检验结果;
@凌驾
公开募捐{
试一试{
callResult=callable.call();
}捕获(例外e){
抛出新的运行时异常(e);
}
}
T startJoinForResult(){
start();
试一试{
join();
}捕捉(中断异常e){
抛出新的运行时异常(e);
}
返回调用结果;
}
}.startJoinForResult();
返回结果;
}
阻止主UI线程有什么意义?如果操作耗时太长,您将得到一个ANR。我需要第二个线程的值,然后才能继续在主线程上工作。我已经在android应用程序中使用AsyncTask,但是如何在mainFunction()中等待另一个线程上的工作完成?设置一个while循环,始终检查工作是否完成?我觉得这很难看。mainFunction()必须从第二个线程返回计算结果。永远不要在主线程中等待。这将导致应用程序无响应。您应该在异步任务的onResult方法中使用结果更新所需的视图。因此,如果要更新文本视图。将该文本视图保存为变量,然后在文本视图的onResult调用setText中保存计算结果。然后我必须将它们链接起来:一个onResult调用另一个异步任务,这个新异步任务的onResult调用另一个异步任务等等。。这是非常非常丑陋的。我只想要一个返回在另一个线程上计算的int值的函数。我已经在android应用程序中使用AsyncTask,但是如何在mainFunction()中等待另一个线程上的工作完成呢?设置一个while循环,始终检查工作是否完成?我觉得这很难看。mainFunction()必须从第二个线程返回计算结果。您不应该在UI线程中等待。我认为mainFunction()应该运行AsyncTask,然后AsyncTask应该在其onPostExecute()方法中返回结果。但接下来我必须将5-6个onPostExecute()链接在一起,因为下一步使用上一步的值。这是非常非常丑陋的。